Typescript 的 keyof 与对象数组

Typescript's keyof with array of objects

我对打字稿还很陌生,很难在 keyof 上找到一些详尽的文档。如果你有

export interface someClassProps<T extends object> {

    /*
        Lets assume T look is an object that looks something like:

        T = {"name": "",
             "val": NaN,
             "active": false}
    */

    A: Array<T>;            // an array of objects
    B: keyof T;             // What type is this? Is just a type of object or is it the keys of T?
    C: keyof Array<T>[0];   // Is this the keys of T?
    D: keyof Array<T>       // Is this type object?
}

BC 你得到什么类型?我希望从 keyof 中得到一个类型,即 name | val | active。我是在寻找一种看起来像 BC 还是完全不同的方法?

或者是否有一种简单的方法来打印 keyof 中的类型?这样我就可以弄清楚了。

keyof 为您提供给定类型的键的联合类型。例如,如果您有:

export SomeClass implements<{ name: string, val: number, active: boolean}>

...那么 B 将是 "name" | "val" | "active"。在这种情况下,C 也将是 "name" | "val" | "active",因为 Array<T>[0] 是具有 T 元素的数组的第 0 个元素,即 T.

请注意,在 TypeScript 接口的工作方式中,implements 仅表示 "check this implementation is assignable to the interface",默认情况下并未实际设置 class 类型。这意味着如果您愿意,您仍然需要执行 B: "name" | "val" | "active"。您也可以只做 B: "name" 因为该类型可分配给所有键的联合类型。