Home > Software engineering >  TypeScript: How to specify the type of an object's value, if the ':' character is alr
TypeScript: How to specify the type of an object's value, if the ':' character is alr

Time:05-20

I have an object with a key item whose value type could be 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?

CodePudding user response:

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

CodePudding user response:

This should be

const myObj = {x: 0, y: 1, z: 3, item: undefined as boxType };

CodePudding user response:

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