简体   繁体   中英

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 undefined | Box . I have to initiate it as undefined , and at a later time I'll substitute that value with a 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.

So I created a custom type, but I cannot use it because the symbol : is already in use in an 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 ?

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.

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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM