【发布时间】:2018-10-10 01:10:47
【问题描述】:
尝试以递归/嵌套方式实现基本属性为KnockoutObservable<Primitive> 类型的类型:
export type Primitive = string | number | boolean | undefined | null;
export type KnockoutMappedProperty<T> = T extends Primitive ? KnockoutObservable<T> : KnockoutMappedType<T>;
export type KnockoutMappedType<T> = {
[Property in keyof T]: KnockoutMappedProperty<T[Property]>;
};
interface KnockoutObservable<T> extends KnockoutSubscribable<T>, KnockoutObservableFunctions<T> {
(): T;
(value: T): void;
/*...*/
}
调用不带参数的函数编译:
const v1: KnockoutMappedType<{ prop: boolean }> = null;
const propValue: boolean = v1.prop();
如果(value: T): void; 在KnockoutObservable<T> 中不存在,则传递参数不会编译:
v1.prop(true); // Gives compiler error: Expected 0 arguments, but got 1
Intellisense 告诉我 v1.prop 的类型为 KnockoutObservable<true> | KnockoutObservable<false>。为什么某些东西会被拆分成一个应该只是 KnockoutObservable<boolean> 的联合类型?
以下再次编译正常:
const prop: KnockoutObservable<boolean> = v1.prop;
prop(true);
为什么需要引入KnockoutObservable<boolean>类型的变量?
【问题讨论】:
标签: typescript