This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Examples of TypeScript

The use of keyof in TypeScript generics.Copy the code
/ / 1
interface Person {
    name: string;
    age: number;
}
class Student {
    constructor(private info: Person) {}
    getInfo(key: string) {
        return this.info[key]   // Error message}}const student = new Student({
    name: 'bear'.age: 20
});
student.getInfo('name');   // bear
Copy the code

Example 1: The Student class receives data of type Person and stores it in the info variable. There is also a getInfo() method defined to get the corresponding value by key.

Notice that this code will compile successfully in the end, because we get the corresponding value bear by key. This. Info [key] is not the key. The reason is that when we pass a key to getInfo(), there is no guarantee that the key is either name or age. If we pass a key other than a key, undefined is returned.

To solve the above problem, a protection mechanism needs to be added.

//
class Student {
    constructor(private info: Person) {}
    getInfo(key: string) {
        if (key === 'name' || key === 'age') {
            return this.info[key]
        }
    }
}
Copy the code

After improvement, there is no error, but there is a problem: Student. GetInfo (‘ name ‘) is of type string | number | undefined, because we pass the key value, the type of return is uncertain, TypeScript not more depth to help us determine, At least roughly analyze whether the value passed in could be name, it could be age, or something else. It still doesn’t look perfect.

// Example 1
class Student {
    constructor(private info: Person) {}
    getInfo<T extends keyof Person>(key: T): Person[T]{
        return this.info[key]
    }
}
Copy the code

Example 3 uses generics and keyOF syntax to optimize the previous problem. Keyof traverses each attribute value of the Person interface once, but this code still looks complicated. After the optimization, the key type is string if it is name. When the key is age, it is of type number, which is already the best way to write it.

If there is an object in a class and you need to get an item of the object based on the index or key value and infer the type of the returned item, you can use the T extends Keyof Person syntax in Example 3.

Finish this! If this article helps you at all, please give it a thumbs up.