我有一个ValueLike<T>
类型,它只是值访问的包装器(值可以直接访问,也可以通过数组中的延迟索引视图访问).我还有一个ScalarLike<T>
类型,它表示特定T
的ValueLike<T>
多个方法.例如,Num
类实现了ScalarLike<number>
,并且有加法、除法等方法.最后,我有一个VariableLike<T>
(=数组)类型,我可以从中访问并推送相应的ScalarLike
.
根据我的推理,Num
是一个比ScalarLike<number>
更窄的类型,因此它应该可以作为参数赋值给VariableLike<number>
的Push方法.但是,当我try 这样做时,我得到以下错误:
type ValueLike<T> = {
value: () => T;
};
class Value<T> implements ValueLike<T> {
constructor(private val: T) {}
value = () => this.val;
}
class View<T> implements ValueLike<T> {
constructor(private array: T[], private index: () => number) {}
value = () => this.array[this.index()];
}
type ScalarLike<T> = {
value: () => T;
};
class Num implements ScalarLike<number> {
constructor(private valueLike: ValueLike<number>) {}
value = () => this.valueLike.value();
add = (other: Num) => new Num(new Value(this.value() + other.value()));
divideBy = (other: Num) => new Num(new Value(this.value() / other.value()));
// ... other methods
}
type VariableLike<T> = {
ith: (index: () => number) => ScalarLike<T>;
push: (scalar: ScalarLike<T>) => number;
};
class NumVariable implements VariableLike<number> {
constructor(private array: number[]) {}
ith = (index: () => number) => new Num(new View(this.array, index));
push = (num: Num) => { // Error: Type 'ScalarLike<number>' is missing the following properties from type 'Num': valueLike, add, divideBy
return this.array.push(num.value());
};
}
(抱歉,代码块很长,但我想,否则可能不清楚我要做的是什么)
你知道我做错了什么吗?