Closed
Description
The in operator provides an opportunity for us to narrow a type. There are two ways that this could work:
- We can select particular constituents of a union type based on which members are present:
interface I1 {
p: string;
}
interface I2 {
q: string;
}
var v: I1 | I2;
if ("p" in v) {
v.p; // Error
}
- If we have a general type like Object, we can clone the type and add a specific property to it when narrowing:
var v: Object;
if ("p" in v) {
v.p; // Type should be { p: any }
}