[英]TypeScript: How to specify the type of an object's value, if the ':' character is already reserved?
I have an object with a key item
whose value type could be undefined | Box
我有一个 object,它有一个值类型可能未定义的键
item
undefined | Box
undefined | Box
. undefined | Box
。 I have to initiate it as undefined
, and at a later time I'll substitute that value with a Box
.我必须将其初始化为
undefined
,稍后我将用Box
替换该值。
const myObjs = {
"obj1" : {x: 0, y: 1, z: 3, item: undefined},
"obj2" : {x: 0, y: 1, z: 3, item: undefined}
};
This gives me the error这给了我错误
Object literal's property 'item' implicitly has an 'any' type.
Object 文字的属性“item”隐式具有“any”类型。
So I created a custom type, but I cannot use it because the symbol :
is already in use in an object:所以我创建了一个自定义类型,但我不能使用它,因为符号
:
已经在 object 中使用:
type boxType = undefined | Mesh;
const myObjs = {
"obj1" : {x: 0, y: 1, z: 3, item: boxType: undefined},
"obj2" : {x: 0, y: 1, z: 3, item: boxType: undefined}
};
How do I tell my object that item
should be of type boxType
?我如何告诉我的 object 该
item
应该是boxType
类型?
This should be这应该是
const myObj = {x: 0, y: 1, z: 3, item: undefined as boxType };
Either list out all the properties together要么一起列出所有属性
const myObj: {
x: number;
y: number;
z: number;
item: undefined | Mesh;
} = { x: 0, y: 1, z: 3, item: undefined };
or, more concisely but requiring an ugly type assertion, use as
after the item.或者,更简洁但需要丑陋的类型断言,在项目之后使用
as
。
const myObj = {x: 0, y: 1, z: 3, item: undefined as undefined | Mesh };
I would strongly suggest just typing everything:我强烈建议只输入所有内容:
type Mesh = any;
type ObjectType = {
x: number;
y: number;
z: number;
item?: Mesh; // Mesh or undefined
}
const myObjs: {[key: string]: ObjectType} = {
"obj1" : {x: 0, y: 1, z: 3},
"obj2" : {x: 0, y: 1, z: 3, item: undefined} // if you *really* need this
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.