我正在开发一个游戏,并尝试将其模式定义为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[];
}
有什么想法吗?
答案 0 :(得分:1)
您的代码有几个问题,(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" },
]
},
}]
}
}
}