What does the `in` keyword do in typescript?
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, andobjectName
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; }