【发布时间】:2018-11-09 23:29:00
【问题描述】:
我有以下课程.....
export class Person<T, C = T> {
lens: any = null;
private value: T;
constructor(value: T, newLens?: any) {
this.value = value;
this.lens = newLens;
}
at<K extends keyof C>(path: keyof C): Person<T, C[K]> {
if(!this.lens) {
return new Person<T, C[K]>(this.value, Lens.lens(path));
}
return new Person<T, C[K]>(this.value, Lens.compose(this.lens)(Lens.lens(path)));
}
get(): any {
if(!this.lens) return this.value;
return Lens.get(this.lens)(this.value);
}
set(f: (newValue: any) => any): T {
return Lens.set(this.lens)(f(this.get()))(this.value);
}
}
我的问题是,当我尝试在一个对象上使用我的新 Person 类时,我得到了不正确的行为.....
const TestPerson = {
name: {
name: "steve"
},
siblings: [{name: "shanon"}]
age: Infinity
}
const test = new Person(TestPerson).at("name").at("name") // works....
const test2 = new Person(TestPerson).at("siblings").at(0) // fails
const test3 = new Person(TestPerson).at(siblings").at("0") // still fails.
const test4 = new Person(TestPerson).at("nonexistantproperty") //correctly fails.
我的问题是我需要一个可以处理 keyof 对象和 keyof 数组的“AT”函数,但似乎无论我如何重做它都无法实现。
在我看来,这似乎是 typescript 的一个巨大缺陷,数组和对象都只是底层的对象,因此对象类型上的 keyof 和数组类型上的 keyof 应该以相同的方式工作。
【问题讨论】:
标签: typescript typescript-typings typescript-types