1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So this function is being used in a way that i don't know what the keys of the object are. Is B always guaranteed to be the same as C if Array<T> is an array of objects? Or is it keyof Array<T> just going to be of type object?
keyof Array<T> is different than keyof Array<T>[0] since the former would be the union type of all keys of Array including array methods. Otherwise it will be the T object.
Ah i see. So i've added a new typeD to my example. In my example B and C are the same type, but D is not?
Type D would essentially be the union of "includes" | "length" | "map", etc. i.e. you probably don't want to use that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.