Javascript 如何创建一个通用的TypeScript接口,该接口匹配任何类型/接口/对象,并对其中的值的类型进行限制?
我想创建一个通用的TypeScript接口,它匹配任何类型、接口或对象,并对其中的值的类型进行限制 下面是Javascript 如何创建一个通用的TypeScript接口,该接口匹配任何类型/接口/对象,并对其中的值的类型进行限制?,javascript,typescript,object,types,interface,Javascript,Typescript,Object,Types,Interface,我想创建一个通用的TypeScript接口,它匹配任何类型、接口或对象,并对其中的值的类型进行限制 下面是MyInterface,它具有属性fooIProp和barIProp,存储字符串,示例如下: interface MyInterface { fooIProp: string; barIProp: string; }; const testInterface: MyInterface = { fooIProp: "foo", barIProp: &qu
MyInterface
,它具有属性fooIProp
和barIProp
,存储字符串,示例如下:
interface MyInterface {
fooIProp: string;
barIProp: string;
};
const testInterface: MyInterface = {
fooIProp: "foo",
barIProp: "bar"
};
type MyType = {
fooTProp: string;
barTProp: string;
}
const testType: MyType = {
fooTProp: "foo",
barTProp: "bar"
}
下面是MyType
type别名,它具有属性footrop
和barTProp
,存储字符串,示例如下:
interface MyInterface {
fooIProp: string;
barIProp: string;
};
const testInterface: MyInterface = {
fooIProp: "foo",
barIProp: "bar"
};
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接口,该接口可以匹配任何类型/接口/对象,并对其内部的值的类型进行限制?这是一个已知的问题(目前正在按预期工作),它没有添加到接口
类型的值中,而它们是为匿名对象类型添加的。请参阅以进行讨论
从技术上讲,以这种方式添加隐式索引签名是不安全的。TypeScript中的对象类型是开放的/可扩展的,而不是封闭的/精确的(有关精确类型的讨论/请求,请参阅),因此除了界面中提到的已知属性之外,始终可以拥有属性:
const someObject = {
fooIProp: "foo",
barIProp: "bar",
baz: 12345
};
const unexpectedMyInterface: MyInterface = someObject; // no error
(尽管如果您试图直接在带注释的对象文字中添加此类未知属性,您将收到警告,这有时会使TypeScript中的对象类型看起来精确,而实际上它们并不精确)
unexpectedMyInterface
可分配给MyInterface
,但不能分配给MyGenericInterface
,这就是为什么禁止分配在技术上是正确的。当然,您可以使用MyType
进行相同的练习:
const someOtherObject = {
fooTProp: "foo",
barTProp: "bar",
baz: 12345
};
const unexpectedMyType: MyType = someOtherObject;
…但是,unexpectedMyType
到MyGenericInterface
的错误分配是允许的:
const badMyGenericInterface:MyGenericInterface=unexpectedMyType;
console.log(badMyGenericInterface.baz?.toUpperCase());//TS中没有错误,但是
//运行时用例是中讨论的较窄的类型