【发布时间】:2021-11-14 11:34:43
【问题描述】:
我在 typescript 中有一个类型,它是一个对象,它的所有属性都应该是 number 类型。基于这种类型,我想创建比原始类型更具体的各种接口,并将它们作为泛型参数传递给一个类,该类除了扩展我的基本类型的泛型,但我总是收到以下打字稿错误:
类型“yyy”中缺少类型“xxx”的索引签名
在打字稿中是否可以做类似于我想做的事情?我能做到的最好的事情是告诉我的moreConcrete 接口,它扩展了basic 类型,这样,错误就消失了,但是在尝试使用该接口时我失去了自动完成和其他智能感知功能。
这里有一个例子:Fiddle
这是小提琴中的代码:
type basic = {
[key: string]: number
}
class A<TInput extends basic> {
}
interface moreConcrete {
a: number,
b: number
}
const test = new A<moreConcrete>(); // this does not work like this
interface otherMoreConcrete extends basic {
a: number,
b: number
}
const test2 = new A<otherMoreConcrete>(); // this does not give any errors
const typeTest: keyof otherMoreConcrete = 'as'; // this accepts as as a key of otherMoreConcrete, because of the extension to `basic`, this should be an error
【问题讨论】:
-
@kaya3 在课堂上省略了接口的使用,因为没有它也可以重现问题。我原来的
basic界面在实际代码中也不是那么简单,这只是为了尝试以一种简单的方式显示我遇到的问题。基本上,我需要的是,我可以定义一个限制扩展该类型的接口的类型吗? -
你可以限制类的泛型参数,所以如果你传递非数字成员
class A<T extends Record<keyof T, number>>typescriptlang.org/play?#code/…的东西会出错
标签: typescript