Typescript index signature any - only works with `any`?

I have an interface and a class:

export interface State {
    arr : any[];
}


export const INITIAL_STATE: State = {
    arr: []
};

It compiles.

Now I use an interface like:

export interface State {
    arr : any[];
    [key: string]: any
}

And the class should look like this:

export const INITIAL_STATE: State = {
    arr: []    ,
    'a':2
};

- compiles.

But now - if I want to be more strict in: [key: string]: any---> [key: string]: number:

In other words:

export interface State {
    arr : any[];
    [key: string]: number
}


export const INITIAL_STATE: State = {
    arr: []    ,
    'a':2
};

I get an error message:

Error: (7, 14) TS2322: Type '{arr: undefined []; 'number; } 'is not assigned to the type' State '. Property 'arr' incompatible with index signature. The type 'undefined []' cannot be assigned to the type 'number'.

Question:

Why is this? I do not understand the logic of this restriction. What can I do to solve this problem?

+4
source share
1 answer

The following interface:

export interface State {
    arr : any[];
    [key: string]: number
}

, :

'arr' 'any []' ''

, [key: string]: number, TypeScript , , . , , :

export interface State {
    [key: string]: number | any[]
}

, , :

export interface State {
    arr : any[];
    [key: string]: any
}

, [key: string]: any TypeScript " ", , " ". arr : any[]; .

+1

Source: https://habr.com/ru/post/1691537/


All Articles