【发布时间】:2020-03-24 19:06:35
【问题描述】:
有两种:
type ExcludeString<T = any> = Exclude<T, string>;
type ExcludeStringAndBoolean<T = any> = Exclude<T, string | boolean>;
在函数的代码中
function test1<T>(p: ExcludeStringAndBoolean<T>) {
let a: ExcludeString<T>;
a = p;
}
tsc 为行 a = p 抛出错误
Type 'Exclude<T, string | boolean>' is not assignable to type 'Exclude<T, string>'.ts(2322)
但对于某些用途来说效果很好:
type CertainType = string | number | boolean;
function test2(p: ExcludeStringAndBoolean<CertainType>) {
let a: ExcludeString<CertainType>;
a = p;
}
为什么会这样?
【问题讨论】:
-
有趣的案例。出于好奇将代码复制到 TS playground:link
标签: typescript typescript-typings typescript-generics