1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Type 'number' is not assignable to type '{ name: string; hex: string; }[]'.(2322) in angular

Discussão em 'Angular' iniciado por user1169587, Maio 30, 2025.

  1. user1169587

    user1169587 Guest

    angular

    COLORS is defined as follow in file colors.ts:

    export const COLORS = [
    {
    name: 'Absolute Zero',
    hex: '#0048BA',
    },
    {
    name: 'Acid Green',
    hex: '#B0BF1A',
    },
    ];


    then in app.component.ts, there is a function as follow:

    import { COLORS } from './colors';
    .....
    .....
    export class AppComponent {
    colors = COLORS;

    addColor(input: HTMLInputElement): void {
    console.log(input.value);
    if (!input.value) {
    return;
    }
    console.log('typeof this.colors =' + typeof this.colors);
    console.log('Array.isArray(this.colors)=' + Array.isArray(this.colors));
    const newColor = { name: input.value, hex: Math.random().toString() };
    console.log('typeof newColor =' + typeof newColor);
    console.log('Array.isArray(newColor)=' + Array.isArray(newColor));
    this.colors = this.colors.push(newColor); <= error here
    input.value = '';
    }

    colorTrackBy(index, color) {
    return color.hex;
    }
    }


    there is error


    Error in src/app/app.component.ts (21:5) Type 'number' is not assignable to type '{ name: string; hex: string; }[]'.
    ​

    Why this.colors is type 'number'? I expect this.colors should be equals to type COLORS, that is an object array '{ name: string; hex: string; }[]'

    Continue reading...

Compartilhe esta Página