【发布时间】:2022-01-20 07:34:24
【问题描述】:
为什么这个 TypeScript 代码...
interface Base {
prop1: string
}
interface Derived extends Base {
prop2: string
}
class Collection<T> {
items: T[] = []
add(item: T): T {
this.items.push(item)
return item
}
}
const col = new Collection<Base>()
col.add({
prop1: 'value1',
prop2: 'value2'
})
// Note this work around, which demonstrates that this is perfectly workable without the typing
console.log(
(
col.add({
prop1: 'value1',
prop2: 'value2'
} as any) as any
)
.prop2
)
(见here)
...产生这个错误...
Argument of type '{ prop1: string; prop2: string; }' is not assignable to parameter of type 'Base'.
Object literal may only specify known properties, but 'prop2' does not exist in type 'Base'. Did you mean to write 'prop1'?
更具体地说,我如何指定我想创建一个Collection 的实例,它接受Base 类型的项目以及任何和所有派生接口类型(但没有其他类型)而不指定所有派生类型的联合?
根据目前的回复,我猜想这在当前 (4.5.4) 版本的 TypeScript 中是不可能的。
【问题讨论】:
-
呃,你在做什么把
string作为WeakMap的键?这会给你一个运行时错误,TypeScript 也不喜欢它(从string扩大到对象包装器String不是解决这个问题的方法)。由于您的问题显然与此类事情无关,您可以edit 删除它吗?你可以只使用普通的Map而不是WeakMap,对吧? -
TypeScript 不喜欢
string,但可以使用String。在这里使用字符串似乎有助于使示例保持简单。 -
您明白您的示例虽然简单,但在运行时会爆炸,对吗?你希望这种情况发生吗?如果没有,你能解决它吗?如果是这样,为什么?如果你不关心,你能修复它吗(这样其他人就不必弄清楚它发生了什么)?
-
无论如何this 是我在这里回答的方法,但它可能与Alex Wayne's answer 的区别不足以打扰。祝你好运!
-
已更新。希望这个新的例子更受欢迎。
标签: typescript