代码之家  ›  专栏  ›  技术社区  ›  Allyl Isocyanate

使用Typescript定义对象架构时出错

  •  0
  • Allyl Isocyanate  · 技术社区  · 6 年前

    我正在研究一个游戏,并试图将它的模式定义为Typescript中的一组类型:

    interface Outcome {
      Difference: string,
      Room: string
    };
    
    interface Movement {
      (name: string): {
        Points: number,
        Exits: Array<Outcome>
      }
    };
    
    interface Room {
      (name: string): {
        Movements: Array<Movement>
      }
    };
    
    interface Rooms {
      (name: Room)
    };
    
    interface Definitions {
      Rooms: Rooms
    };
    
    const defs: Definitions = {
      Rooms: {
        "Kitchen": {
          Movements: [
            "Living Room": {
              Points: 3,
              Exits: [
                {Difference: "<= 1", Room: "Bedroom"},
                {Difference: "2", Room: "Living Room"},
              ]
            },
            Bedroom: {
              Points: 2,
              Exits: [
                {Difference: "<= 2", Room: "Closet"},
              ]
            },
          ]
        }
      }
    }
    

    我得到以下错误,但不理解问题:

    [ts]
    Type '{ Rooms: { "Kitchen": { Movements: any[]; }; }; }' is not assignable to type 'Definitions'.
      Types of property 'Rooms' are incompatible.
        Type '{ "Kitchen": { Movements: any[]; }; }' is not assignable to type 'Rooms'.
          Object literal may only specify known properties, and '"Kitchen"' does not exist in type 'Rooms'.
    (property) "Kitchen": {
        Movements: any[];
    }
    

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    你的代码有几个问题, (name: string) 定义调用签名,可能需要索引签名: [name: string] ,表示可以使用 [] 任何字符串。

    同时,你的对象文字暗示 Room 接口不是由字符串可索引的,而是具有 Movements 字段。

    这很管用,应该能让你开始:

    interface Outcome {
        Difference: string,
        Room: string
    };
    
    interface Movement {
        [name: string]: {
            Points: number,
            Exits: Array<Outcome>
        }
    };
    
    interface Room {
        Movements: Array<Movement>
    };
    
    interface Rooms {
        [name: string]: Room
    };
    
    interface Definitions {
        Rooms: Rooms
    };
    
    const defs: Definitions = {
        Rooms: {
            "Kitchen": {
                Movements: [{
                    "Living Room": {
                        Points: 3,
                        Exits: [
                            { Difference: "<= 1", Room: "Bedroom" },
                            { Difference: "2", Room: "Living Room" },
                        ]
                    },
                    Bedroom: {
                        Points: 2,
                        Exits: [
                            { Difference: "<= 2", Room: "Closet" },
                        ]
                    },
                }]
            }
        }
    }
    

    Playground link