简体   繁体   中英

Type syntax - What's the meaning of this syntax in Typescript

I'm new to Typescript; I don't understand the meaning of this syntax; can anybody explain it to me?

type Type1<K> = K extends string ? { [P in K]: string } : never;

If type K extend string, than Type1 will be a document of array of strings? Something like:

{"x": ["a", "b", "c"],
 "z": ["d", "e", "f"]
//etc
}
Or
{"x": "a",
    "z": "b"
//etc
}

Let first look at { [P in K]: string } this is a mapped type. If K is a union of string literal types (ex: 'a' | 'b' ) the result of this type will be an object type with those names as keys and of string type (so { a: string, b: string } ). This is actually equivalent to the predefined Record type.

The K extends string ? ... : never K extends string ? ... : never is a distributive conditional type . This means that if K is union type, each member of the union will be taken and put through the mapped type. So for example:


type ex = Type1<'a' | 'b'> => 
    ('a' extends string ? { [P in 'a']: string } : never) | ('b' extends string ? { [P in 'b']: string } : never) =>
    ({ [P in 'a']: string }) | ({ [P in 'b']: string }) => 
    { a: string } | { b: string }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM