打字稿-条件映射类型

时间:2018-10-17 01:00:37

标签: typescript knockout.js

我想使用Knockout可观察对象将普通的旧Javascript类型映射到等效类型。

interface KnockoutObservableArray<T> { }
interface KnockoutObservable<T> { }

class CustomerDto {
    Name: string;
    PetLicenseNumbers: number[];
}

// manually mapped to Knockout-equivalent 
class CustomerDtoKo {
    Name: KnockoutObservable<string>;
    PetLicenseNumbers: KnockoutObservableArray<number>;
}

我正在尝试使用映射类型自动执行上述操作,但我无法 找到适当的方法来有条件地将数组映射到KnockoutObservableArray<U> 同时将标量映射到KnockoutObservable<U>

type KnockoutType<T> = {
    //[K in keyof T] : KnockoutObservableArray<T[K][0]>
    [K in keyof T] : KnockoutObservable<T[K]>
}

type CustomerDtoKo2 = KnockoutType<CustomerDto>;
// gives
type CustomerDtoKo2 = {
    Name: KnockoutObservable<string>,
    PetLicenseNumbers: KnockoutObservable<number[]> // should be KnockoutObservableArray<number>
}

1 个答案:

答案 0 :(得分:3)

如您所料,conditional types将为您提供帮助:

type KnockoutType<T> = {
    [K in keyof T]: T[K] extends Array<infer U> ? 
      KnockoutObservableArray<U> : KnockoutObservable<T[K]>
}

祝你好运!