How to understand TypeScript intersection through keyof
P粉451614834
2023-09-05 22:37:33
<p><pre class="brush:php;toolbar:false;">interface Person {
name: string;
}
interface Lifespan {
birth: Date;
death: Date;
}
type PersonSpan = Person & Lifespan;
type K = keyof PersonSpan; // type K = "name" | "birth" | "death"
let prop: K = "name"; // ok
let obj: PersonSpan = { // compile error, missing birth and death properties
name: "John Smith"
}</pre>
<p>If I want to understand type intersection via <code>keyof</code>: </p>
<p>The key<code>{ name: "John Smith" }</code> of this object instance is <code>name</code>, which matches the <code>keyof PersonSpan</code> , that is, <code> "name" | "birth" | "death" </code>, it is valid to execute <code>let prop: "name" |. "Birth" | "Death" = "Name"; </code></p>
<p>So as long as the object has one of these three properties it should be valid, why does it still need to have all properties assignable to <code>PersonSpan</code>? </p>
In TypeScript, when you define a type using the intersection & of two or more types, the resulting type will have all the properties of each intersection type. In this case, PersonSpan is defined as the intersection of Person and Lifespan, so an object of type PersonSpan must have all the properties of Person and Lifespan. Even if keyof PersonSpan results in "name" | "birth" | "death", this does not mean that any object with only one of these properties is valid for PersonSpan, it means that the type K you initialized is the union of the PersonSpan property names. Set, you can access these properties using the key "name" on an object of type PersonSpan, "birth" or "death" which may also be the Partial type you are looking for, which makes all props optional