How to understand TypeScript intersection through keyof
P粉451614834
P粉451614834 2023-09-05 22:37:33
0
1
362

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" }

If I want to understand type intersection via keyof:

The key{ name: "John Smith" } of this object instance is name, which matches the keyof PersonSpan , that is, "name" | "birth" | "death" , it is valid to execute let prop: "name" |. "Birth" | "Death" = "Name";

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 PersonSpan?

P粉451614834
P粉451614834

reply all (1)
P粉267791326

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

let obj: Partial = { name: "John Smith" }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!