TypeScript对象类型

manueld4722623

我正在尝试将我的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我需要什么类型的提前致谢!

大卫4

首先,您不应该使用数字枚举,因为它是不安全的(您可以为其分配任何数字)。请改用字符串枚举或字符串联合。

这是使用字符串枚举的解决方案:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章