代码之家  ›  专栏  ›  技术社区  ›  M -

TypeScript:如果“:”字符已被保留,如何指定对象值的类型?

  •  0
  • M -  · 技术社区  · 4 年前

    我有一个带钥匙的物体 item 其值类型可以是 undefined | Box 。我必须作为 undefined ,稍后我将用 Box .

    const myObjs = {
        "obj1" : {x: 0, y: 1, z: 3, item: undefined},
        "obj2" : {x: 0, y: 1, z: 3, item: undefined}
    };
    

    这给了我错误

    对象文字的属性“item”隐式具有“any”类型。

    所以我创建了一个自定义类型,但我不能使用它,因为符号 : 已在对象中使用:

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

    我该如何告诉我的对象 项目 应为类型 boxType ?

    3 回复  |  直到 4 年前
        1
  •  1
  •   Robby Cornelissen    4 年前

    我强烈建议只需键入所有内容:

    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
    };
    
        2
  •  1
  •   CertainPerformance    4 年前

    要么将所有属性一起列出

    const myObj: {
      x: number;
      y: number;
      z: number;
      item: undefined | Mesh;
    } = { x: 0, y: 1, z: 3, item: undefined };
    

    或者,更简洁但需要难看的类型断言,使用 as 在项目之后。

    const myObj = {x: 0, y: 1, z: 3, item: undefined as undefined | Mesh };
    
        3
  •  1
  •   M -    4 年前

    这应该是

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