【发布时间】:2021-04-26 03:45:50
【问题描述】:
我想创建一个通用 TypeScript 接口,它匹配任何类型或接口或对象,但其中的值的类型有限制。
这里是MyInterface,它具有fooIProp 和barIProp 的属性,其中存储了一个示例字符串:
interface MyInterface {
fooIProp: string;
barIProp: string;
};
const testInterface: MyInterface = {
fooIProp: "foo",
barIProp: "bar"
};
这里是MyType 类型别名,它具有属性fooTProp 和barTProp,其中存储字符串的示例:
type MyType = {
fooTProp: string;
barTProp: string;
}
const testType: MyType = {
fooTProp: "foo",
barTProp: "bar"
}
这是一个具有属性fooObjectKey 和barObjectKey 的对象,用于存储字符串:
const testObject = {
fooObjectKey: "foo",
barObjectKey: "bar"
}
我创建了MyGenericInterface,它接受带有字符串作为键和值的对象,如下所示:
interface MyGenericInterface { [key: string]: string }
然后我尝试将testInterface 分配给MyGenericInterface
const testFromInterface: MyGenericInterface = testInterface;
const testFromType: MyGenericInterface = testType;
const testFromObject: MyGenericInterface = testObject;
它会抛出 TS2322 错误:
Type 'MyInterface' is not assignable to type 'MyGenericInterface'.
Index signature is missing in type 'MyInterface'.(2322)
这里是TypeScript Playground 供参考。
问题:如何创建一个通用的 TypeScript 接口,它可以匹配任何类型/接口/对象,但对其中的值类型有限制?
【问题讨论】:
标签: javascript typescript object types interface