dot*_*141 4 generics typescript typescript-generics union-types conditional-types
我有以下类型声明:
class MyGeneric<T> { }
type ReplaceType<T> = T extends Function ? T : MyGeneric<T> | T;
Run Code Online (Sandbox Code Playgroud)
ReplaceType<T>应该解析为MyGeneric<T> | TorT取决于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>;
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不能正确地与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">;
Run Code Online (Sandbox Code Playgroud)
boolean和 联合具有相似行为的原因是因为编译器将和boolean视为文字类型的联合,所以(尽管这个定义并不显式存在)truefalsetype 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">;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
411 次 |
| 最近记录: |