TypeScript
是否有办法将对象文字的属性分配给某个类型?
考虑以下示例:
interface ILiteralType
{
// I don't know what is going to be part of this object
// but I know it should be of type string.
*: string;
}
class MyClass
{
properties: ILiteralType;
}
var m = new MyClass();
m.properties = {
name: "A name", // ok
age: 10, // error: Should be a string
anotherProp: "some value" // ok too
...
};
答案 0 :(得分:1)
我认为你正在寻找这个:
interface ILiteralType
{
[property: string]: string;
}
这将要求所有属性值都是字符串。