联合类型和条件类型的问题

时间:2018-07-16 15:35:32

标签: typescript generics typescript-generics union-types conditional-types

我有以下类型声明:

class MyGeneric<T> { }

type ReplaceType<T> = T extends Function ? T : MyGeneric<T> | T;

ReplaceType<T>应该解析为MyGeneric<T> | TT,具体取决于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">;

Playground link

1 个答案:

答案 0 :(得分:2)

boolean和并集具有相似行为的原因是因为编译器将boolean视为文字类型为truefalse的并集,因此{{1} }(尽管此定义不明确存在)

该行为的原因是,根据设计,条件类型分布在联合上。这是设计好的行为,可以实现各种强大的功能。您可以阅读有关主题here

的更多信息

如果您不希望有条件条件在联合上分布,则可以在元组中使用该类型(这将防止该行为)

type boolean = true | false
相关问题