What does the `in` keyword do in typescript?

后端 未结 1 1605
长情又很酷
长情又很酷 2021-01-01 09:56

I know how to use it, but I cannot find any explanation on it in docs. I\'d like an accurate definition so that I could understand it better.

Edit: I mean the

相关标签:
1条回答
  • 2021-01-01 10:38

    This is the standard in Javsacript operator. You can read more documentation here, but the short story is

    The in operator returns true if the specified property is in the specified object. The syntax is:

    propNameOrNumber in objectName
    

    where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

    In Typescript the in operator also acts as a type guard as described here

    interface A {
      x: number;
    }
    interface B {
      y: string;
    }
    
    let q: A | B = ...;
    if ('x' in q) {
      // q: A
    } else {
      // q: B
    }
    

    Edit

    An alternative meaning of in in typescript is in mapped type definition. You can read about them in the handbook or in the pull request. The in keyword is used there as part of the syntax to iterate over all the items in a union of keys.

    interface Person {
        name: string;
        age: number;
    }
    type Partial<T> = {
        [P in keyof T]?: T[P]; // P will be each key of T
    }
    type PersonPartial = Partial<Person>; // same as { name?: string;  age?: number; }
    
    0 讨论(0)
提交回复
热议问题