Grant Williams
Grant Williams

Reputation: 1537

Typescript's keyof with array of objects

I'm very new to typescript and having a hard time finding some extensive documentation on keyof. If you have

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?
}

What type do you get for B or C? I'm hoping to get a type from keyof that is the would be name | val | active. Am I looking for an approach that looks like B, C, or something fully different?

Alternatively is there an easy way to print the types from keyof? That would allow me to just figure this out.

Upvotes: 1

Views: 6540

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191819

keyof gives you the union type of the keys of the given type. So for example, if you had:

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

...then B would be "name" | "val" | "active". In this case, C would also be "name" | "val" | "active" since Array<T>[0] is 0th element of an array with elements of T which is just T.

Note that with the way TypeScript interfaces work, implements just means "check this implementation is assignable to the interface" and doesn't actually set the class types by default. This means you will still have to do B: "name" | "val" | "active" if you wanted. You could also just do B: "name" since that type is assignable to the union type of all the keys.

Upvotes: 2

Related Questions