简体   繁体   English

Type语法-Typescript中此语法的含义是什么

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

I'm new to Typescript; 我是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? 如果类型K扩展字符串,那么类型1将是字符串数组的文档吗? 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. 首先来看一下{ [P in K]: string }这是一个映射类型。 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 } ). 如果K是字符串文字类型的并集(例如: 'a' | 'b' ),则此类型的结果将是一个以这些名称作为键的string类型的对象类型(所以{ a: string, b: string } )。 This is actually equivalent to the predefined Record type. 这实际上等效于预定义的Record类型。

The K extends string ? ... : never K extends string ? ... : never K extends string ? ... : never is a distributive conditional type . K extends string ? ... : never不是分配条件类型 This means that if K is union type, each member of the union will be taken and put through the mapped type. 这意味着,如果K为联合类型,则将采用联合的每个成员并将其放入映射类型。 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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