我正在尝试将我的JavaScript代码翻译成TypeScript。我不知道如何翻译这些代码:
const COLOR_WHITE = 0;
const COLOR_BLACK = 1;
const CASTLE_TYPE_SHORT = 0;
const CASTLE_TYPE_LONG = 1;
class Game {
constructor() {
this.castling_possibilities = {
COLOR_WHITE: {
CASTLE_TYPE_SHORT: true,
CASTLE_TYPE_LONG: true
},
COLOR_BLACK: {
CASTLE_TYPE_SHORT: true,
CASTLE_TYPE_LONG: true
}
}
}
getCastlingPossibility(color, type) {
return this.castling_possibilities[color][type];
}
}我得到了这段代码,但是有很多错误:
enum Color {
White,
Black
}
enum CastleType {
Short,
Long
}
class Game {
castling_possibilities: Object /* what member type is required? */
constructor() {
this.castling_possibilities = {
Color.White: {
CastleType.Short: true,
CastleType.Long: true
},
Color.Black: {
CastleType.Short: true,
CastleType.Long: true
}
}
}
getCastlingPossibility(color: Color, type: CastleType) : boolean {
return this.castling_possibilities[color][type];
}
}我想要类似于Color的关联数组和CastleType的关联数组,但我不知道如何做到这一点。我需要什么样的castling_possibilities?提前感谢!
发布于 2021-01-17 17:54:50
首先,您不应该使用数字枚举,因为它是不安全的(您可以给它分配任何数字)。使用字符串枚举或字符串联合。
下面是使用string enum的解决方案:
enum Color {
White = 'white',
Black = 'black',
}
enum CastleType {
Short = 'short',
Long = 'long',
}
type Dict = {
[U in Color]: {
[T in CastleType]: boolean;
};
}
class Game {
castling_possibilities: Dict
constructor() {
this.castling_possibilities = {
[Color.White]: {
[CastleType.Short]: true,
[CastleType.Long]: true
},
[Color.Black]: {
[CastleType.Short]: true,
[CastleType.Long]: true
}
}
}
getCastlingPossibility(color: Color, type: CastleType) : boolean {
return this.castling_possibilities[color][type];
}
}发布于 2021-01-17 17:52:40
class Game {
castling_possibilities: Partial<Record<Color, Partial<Record<CastleType, boolean>>>>;
constructor() {
this.castling_possibilities = {
[Color.White]: { [CastleType.Long]: true, [CastleType.Short]: false },
[Color.Black]: { [CastleType.Long]: false, [CastleType.Short]: true }
};
}
getCastlingPossibility(color: Color, type: CastleType): boolean {
return this.castling_possibilities[color]![type]!;
}
}https://stackoverflow.com/questions/65762729
复制相似问题