Javascript 类型脚本对象类型
我正在尝试将我的JavaScript代码转换为TypeScript。 我不知道如何翻译这些代码:Javascript 类型脚本对象类型,javascript,typescript,Javascript,Typescript,我正在尝试将我的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
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];
}
}
我想要像颜色的关联数组和CastleType的关联数组之类的东西,但我不知道怎么做。
我需要什么类型的castleing\u可能性
?
提前谢谢 类游戏{
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]!;
}
}
铸造可能性:局部;
构造函数(){
这是一种可能性={
[Color.White]:{[CastleType.Long]:true[CastleType.Short]:false},
[Color.Black]:{[CastleType.Long]:false[CastleType.Short]:true}
};
}
GetCastlingObability(颜色:颜色,类型:CastleType):布尔值{
返回此。强制转换[color]![type]!;
}
}
首先,您不应该使用数字枚举,因为它不安全(您可以为它分配任何数字)。请改用字符串枚举或字符串联合
以下是使用字符串枚举的解决方案:
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];
}
}