[英]TypeScript definition for array properties
我正在嘗試為具有屬性的數組創建類型。 對於我一生,我無法弄清楚如何為此添加類型(或者即使有可能?)。
// Font weight scale
const fontWeights: FontWeights = [300, 400, 500];
// Font weight aliases
fontWeight.light = fontWeights[0];
fontWeights.normal = fontWeights[1];
fontWeights.bold = fontWeights[2];
我沒有成功嘗試過。
type FontWeightAbsolute = "bold" | "normal" | number;
type Globals = "-moz-initial" | "inherit" | "initial" | "revert" | "unset";
// from https://www.npmjs.com/package/csstype
type FontWeightProperty = Globals | FontWeightAbsolute | "bolder" | "lighter";
export type FontWeights = FontWeightProperty[] & {
light: number;
normal: number;
bold: number;
};
謝謝您的幫助!
數組不能具有屬性
你可以使用枚舉
const enum Direction {
Light = 300,
Normal = 400,
Bold = 500
}
如果您確實想真正了解font-weight
類型(默認CSSStyleDeclaration
font-weight
類型為string
,但是您始終可以做更多事情),則必須包括以下內容:
normal
和bold
等絕對值 bolder
和lighter
inherit
, initial
和unset
如果要執行數字權重值到權重名稱的映射,那將是一個與類型無關的單獨枚舉,因為從技術上font-weight
可以接受任何數值 。
enum FontWeightMapping {
LIGHT = 300,
NORMAL = 400,
MEDIUM = 500,
BOLD = 700
}
type Global = 'initial' | 'inherit' | 'unset';
type FontWeightRelativeNames = 'bolder' | 'lighter';
type FontWeightNames = 'light' | 'normal' | 'medium' | 'bold';
type FontWeight = number | FontWeightRelativeNames | FontWeightNames | Global;
// Then you can do something like this:
let fontWeight: FontWeight;
fontWeight = 100;
fontWeight = FontWeightMapping.LIGHT;
fontWeight = 'light';
您可以這樣做:
type FontWeightAbsolute = "bold" | "normal";
type Globals = "-moz-initial" | "inherit" | "initial" | "revert" | "unset";
type FontWeightAsString =
| Globals
| FontWeightAbsolute
| "bolder"
| "lighter";
enum FontWeightAsNumber {
Light = 300,
Normal = 400,
Bold = 500,
}
type FontWeight = FontWeightAsString | FontWeightAsNumber;
const weights: FontWeight[] = [
'inherit',
400,
FontWeightAsNumber.Bold,
123, // Should not be possible!
];
但這並不完全是類型安全的。 您仍然可以將123
類的數字傳遞給weights
。 類型安全的方法:
declare namespace FontWeight {
type AsString =
| "bold"
| "normal"
type AsNumber =
| 300
| 400
| 500
type Global =
| "-moz-initial"
| "inherit"
| "initial"
| "revert"
| "unset"
}
type Weight =
| FontWeight.AsString
| FontWeight.AsNumber
| FontWeight.Global
const weights: Weight[] = [
300,
400,
'inherit',
"unset"
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.