How to get type of array items?

后端 未结 5 1047
有刺的猬
有刺的猬 2020-11-29 10:03

If I have a type type foo = Array<{ name: string; test: number; }>, would it be possible to get the type of the values within the array, in this case, the

5条回答
  •  我在风中等你
    2020-11-29 10:43

    We can also use an indexed access operator like this:

    const someArray = [
        {
            foo: '',
            bar: '',
            baz: ''
        },
        {
            foo: '',
            bar: '',
            baz: ''
        }
    ];
    
    // indexed access operator
    type SomeArray = typeof someArray[number];
    

    There is a write-up on those here: https://www.typescriptlang.org/docs/handbook/advanced-types.html

    The second operator is T[K], the indexed access operator.

提交回复
热议问题