我希望能夠定義一個具有靜態屬性的類,其中包含一個列舉。我有 JavaScript 在這里作業,我只是想消除型別。下面的簡化示例。
盒子.ts:
enum Color {
RED,
GREEN,
BLUE,
}
export class Box {
static Color = Color;
private color: Color;
constructor(color: Color) {
this.color = color;
}
}
main.ts:
import {Box} from './box';
function createBox(color: Box.Color): Box {
// ERROR: Box.Color isn't a type ^
return new Box(color);
}
const box = createBox(Box.Color.RED);
如上所示,我希望能夠在Color不直接匯入的情況下參考該型別。我想將其作為Box,Box.Color或Box['Color']類似的成員來參考。JavaScriptBox.Color.RED作為一個值可以正常作業,但是我如何參考相對于的型別Box?有什么我可以添加到Box's 的定義中以同時匯出Color型別的嗎?
我不想export enum Color再import {Color}。_ 我想以Box Color某種方式將其稱為一種并且能夠僅傳遞一種Box型別以包含資訊。
我找到了這個解決方案,但它太冗長了:
function createBox(color: (typeof Box.Color)[keyof typeof Box.Color]): Box {
return new Box(color);
}
或者,類似地,但這太過分了:
enum Color {RED, GREEN, BLUE}
class Box {
static Color = Color;
// Defining a value that I don't use works along with `typeof`
// to get the type, but seems like a poor hack and makes
// for a bad API.
static color: Color;
constructor(color: Color) {}
}
function createBox(color: typeof Box.color): Box {
return new Box(color);
}
無論如何將Box類修改為以下或類似的東西?
export class Box {
static Color = Color;
// I want the `Color` type to export as part of the `Box` type.
static type Color: Color;
private color: Color;
constructor(color: Color) {
this.color = color;
}
}
uj5u.com熱心網友回復:
請參閱TypeScript 手冊中的Merging Namespaces with Classes(我已在此答案的末尾行內了完整的檔案部分,以便如果鏈接更改,內容將保留在這里)。針對您問題中的資料量身定制的示例:
TS游樂場
export class Box {
constructor(private color: Box.Color) {}
}
export namespace Box {
export enum Color {
RED,
GREEN,
BLUE,
}
}
function createBox (color: Box.Color): Box {
return new Box(color);
}
const box = createBox(Box.Color.RED);
console.log(box); // { color: 0 }
來自手冊:
將命名空間與類合并
這為用戶提供了一種描述內部類的方式。
class Album {
label: Album.AlbumLabel;
}
namespace Album {
export class AlbumLabel {}
}
合并成員的可見性規則與合并命名空間部分中描述的相同,因此我們必須匯出AlbumLabel類以供合并類查看。最終結果是在另一個類內部管理一個類。您還可以使用命名空間向現有類添加更多靜態成員。
除了內部類的模式,您可能還熟悉創建函式然后通過向函式添加屬性來進一步擴展函式的 JavaScript 實踐。TypeScript 使用宣告合并以型別安全的方式構建這樣的定義。
function buildLabel(name: string): string {
return buildLabel.prefix name buildLabel.suffix;
}
namespace buildLabel {
export let suffix = "";
export let prefix = "Hello, ";
}
console.log(buildLabel("Sam Smith"));
同樣,命名空間可用于擴展具有靜態成員的列舉:
enum Color {
red = 1,
green = 2,
blue = 4,
}
namespace Color {
export function mixColor(colorName: string) {
if (colorName == "yellow") {
return Color.red Color.green;
} else if (colorName == "white") {
return Color.red Color.green Color.blue;
} else if (colorName == "magenta") {
return Color.red Color.blue;
} else if (colorName == "cyan") {
return Color.green Color.blue;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481461.html
標籤:打字稿
上一篇:export{}如何影響宣告全域
下一篇:打字稿錯誤:物件可能未定義
