带类的Typescript多态性



我尝试创建一个函数来创建一个棋子,就像document.createElement:

class pawn extends piece {
}
class bishop extends piece {
}
class rook extends piece {
}
class king extends piece {
}
class queen extends piece {
}
class knigth extends piece {
}
export interface pieces {
"pawn": pawn
"bishop": bishop
"rook": rook
"king": king
"queen": queen
"knigth": knigth
}
export function createPiece<K extends keyof pieces>(pieceName: K, options?: pieceInit): pieces[K]{
/// ???
}

但是我不知道我需要在我的createPiece函数返回什么…我试着

export function createPiece<K extends keyof pieces>(pieceName: K, options?: pieceInit): pieces[K]{
return pieces[pieceName]
}

但我有以下错误:"碎片"仅指一种类型,但被用作值

我的目标是:

const piece1:pawn = createPiece("pawn");
const piece2:queen = createPiece("queen");
.
.
.

您将pieces定义为interface。您只能在编译时访问有关接口的信息,而不能在运行时访问。这就是return pieces[pieceName]行无法编译的原因。

您应该将pieces定义为一个对象。

export const pieces = {
"pawn": pawn,
"bishop": bishop,
"rook": rook,
"king": king,
"queen": queen,
"knigth": knigth
}

可以使用该对象在运行时查找中的键。我们还可以提取pieces的类型信息,以便在编译时使用。

export function createPiece<
K extends keyof typeof pieces
>(pieceName: K): typeof pieces[K] {
return pieces[pieceName]
}

因此,您可以使用typeof pieces来获取pieces对象的类型,而不是直接在泛型类型中使用pieces

游乐场

如果将接口定义为const,则可以。完全输入后,它看起来像这样:

type PiecesKey = keyof Pieces;
type Piece<T extends PiecesKey> = Pieces[T];
type Pieces = {
pawn: pawn;
bishop: bishop;
rook: rook;
king: king;
queen: queen;
knigth: knigth;
};
const pieces = {
pawn: pawn,
bishop: bishop,
rook: rook,
king: king,
queen: queen,
knigth: knigth,
};
type pieceInit = {};
export function createPiece<K extends PiecesKey>(
pieceName: K,
options?: pieceInit,
): Piece<K> {
return new pieces[pieceName]();
}

相关内容

  • 没有找到相关文章

最新更新