typescript - 联合类型和条件类型的问题
问题描述
我有以下类型声明:
class MyGeneric<T> { }
type ReplaceType<T> = T extends Function ? T : MyGeneric<T> | T;
ReplaceType<T>
应该解决MyGeneric<T> | T
或者T
取决于T
它是否是一个函数:
// Input type: string
// Expected type: string | MyGeneric<string>
// Actual type: string | MyGeneric<string>
type Test1 = ReplaceType<string>;
// Input type: () => void
// Expected type: () => void
// Actual type: () => void
type Test2 = ReplaceType<() => void>;
不幸的是,这不适用于boolean
和联合类型:
// Input type: boolean
// Expected type: boolean | MyGeneric<boolean>
// Actual type: boolean | MyGeneric<true> | MyGeneric<false>
type Test3 = ReplaceType<boolean>;
// Input type: "foo" | "bar"
// Expected type: "foo" | "bar" | MyGeneric<"foo" | "bar">
// Actual type: "foo" | "bar" | MyGeneric<"foo"> | MyGeneric<"bar">
type Test4 = ReplaceType<"foo" | "bar">;
解决方案
原因boolean
和联合具有相似的行为是因为编译器将boolean
其视为文字类型的联合true
,false
因此type boolean = true | false
(尽管此定义不明确存在)
该行为的原因是通过设计条件类型分布在联合上。这是设计的行为,允许实现各种强大的东西。您可以在此处阅读有关该主题的更多信息
如果您不希望条件分布在联合上,您可以在元组中使用该类型(这将阻止该行为)
class MyGeneric<T> { }
type ReplaceType<T> = [T] extends [Function] ? T : MyGeneric<T> | T;
// Input type: string
// Expected type: string | MyGeneric<string>
// Actual type: string | MyGeneric<string>
type Test1 = ReplaceType<string>;
// Input type: () => void
// Expected type: () => void
// Actual type: () => void
type Test2 = ReplaceType<() => void>;
// Input type: boolean
// Expected type: boolean | MyGeneric<boolean>
// Actual type: boolean | MyGeneric<boolean>
type Test3 = ReplaceType<boolean>;
// Input type: "foo" | "bar"
// Expected type: "foo" | "bar" | MyGeneric<"foo" | "bar">
// Actual type: "foo" | "bar" | MyGeneric<"foo" | "bar">
type Test4 = ReplaceType<"foo" | "bar">;
推荐阅读
- sql-server - 使用 LINQ 在左连接表中按特定列求和时排除空值
- scala - 如何将源映射到另一个?
- batch-file - 从 ansible 控制主机执行批处理脚本无法正常工作
- macos - 如何修复错误无法加载供应商库 [libfbclient.dylib 或 libfbembed.dylib]
- typescript - 要求子对象属性值与父键的类型相同
- reactjs - 未定义的反应本机错误不是对象
- python - 第四行下面的代码是什么,你如何在 a 加 a 的 A p 中做 B ?
- r - 根据R中另一个单元格中的值用NA替换一个单元格
- python-3.x - 保存和加载 pytorch 神经网络
- php - 将日文字符保存到 MySQL