Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 为什么TS泛型类型会根据下面的代码运行两次?_Typescript - Fatal编程技术网

Typescript 为什么TS泛型类型会根据下面的代码运行两次?

Typescript 为什么TS泛型类型会根据下面的代码运行两次?,typescript,Typescript,我们可以从每个示例的结果中看到差异,“泛型类型”是如何工作的,单独使用“扩展”有什么不同 type NameOrId<T> = T extends number ? 'add' : 'plus'; type foo = string | number; type x = NameOrId<foo> // x is 'add' | 'plus' type bar = foo extends number ? 'add' : 'plus' // bar is 'plus'

我们可以从每个示例的结果中看到差异,“泛型类型”是如何工作的,单独使用“扩展”有什么不同

type NameOrId<T> = T extends number ? 'add' : 'plus';
type foo = string | number;

type x = NameOrId<foo>
// x is 'add' | 'plus'

type bar = foo extends number ? 'add' : 'plus'
// bar is 'plus'

type zoo = foo extends number | string ? 'add' : 'plus'
// zoo is 'add'
类型NameOrId=T扩展数字?“加':'加';
foo类型=字符串|编号;
类型x=名称ORID
//x是“加上”|“加上”
类型bar=foo扩展编号?“加上“:”加上“
//酒吧是“加号”
类型zoo=foo扩展数字|字符串?'加上“:”加上“
//动物园是“添加”
此行为在以下的TypeScript文档中:

当条件类型作用于泛型类型时,当给定一个联合类型时,它们将成为分布式的

它还解释了如何防止分发:

通常,分配性是期望的行为。为了避免这种行为,可以用方括号括住extends关键字的每一侧

其工作原理如下所述:

//将T括在方括号中,以避免条件分布在联合类型的成员上
类型NameOrId=[T]扩展了数字?'加':'加';
类型y=名称ORID;
//y是“加号”
检查它。

此行为在以下的TypeScript文档中:

当条件类型作用于泛型类型时,当给定一个联合类型时,它们将成为分布式的

它还解释了如何防止分发:

通常,分配性是期望的行为。为了避免这种行为,可以用方括号括住extends关键字的每一侧

其工作原理如下所述:

//将T括在方括号中,以避免条件分布在联合类型的成员上
类型NameOrId=[T]扩展了数字?'加':'加';
类型y=名称ORID;
//y是“加号”
检查一下