在联合上分配通用类型

问题描述

TS中是否有一种方法可以通过联合“分布”泛型?

type Container<A> = { value: A };

type Containers<string | number> = Container<string> | Container<number>

(假设我们从上下文中知道何时应用ContainersContainer

解决方法

令人惊讶的是,类型推断将为您做到这一点:

type Container<T> = { value: T }

type Containers<T> = T extends infer A ? Container<A> : never;

编译器足够聪明,可以将它们全部解开:

type C = Containers<string | number | {x: number} | {z: string} | boolean>

类型C扩展了以下方式:

type C = Container<string> | 
         Container<number> | 
         Container<false> | 
         Container<true> | 
         Container<{
           x: number;
         }> | 
         Container<{
           z: string;
         }>

ts-playground

,

鉴于您的示例代码,我认为您想定义一个约束为类型联合的泛型类型。其中之一应该适合您的账单。

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    let welcome = try decoder.decode(Welcome.self,from: data)
    completion(welcome,nil)
} catch let jsonError {
    print("Failed to decode JSON: \(jsonError)")
    completion(nil,jsonError)
}

还要注意,Spread是JavaScript中的语法规则。在您的问题中,它的用法令人困惑。