数组属性的TypeScript定义

时间:2019-01-12 12:59:51

标签: typescript

我正在尝试为具有属性的数组创建类型。对于我一生,我无法弄清楚如何为此添加类型(或者即使有可能?)。

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

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

数组不能具有属性

您可以使用枚举

const enum Direction {
    Light = 300,
    Normal = 400,
    Bold = 500
}

答案 1 :(得分:0)

如果您真的想对font-weight进行打字(默认的CSSStyleDeclaration的{​​{1}}键入为font-weight,但您可以做更多的事情),您将必须包含以下内容:

  • 接受stringnormal之类的绝对值
  • 接受boldbolder之类的相对值
  • 接受任何数值
  • 全局值,例如lighterinheritinitial

如果您要执行数字重量值到重量名称的映射,那将是一个与类型无关的单独枚举,因为从技术上unset可以接受任何数值

font-weight

答案 2 :(得分:0)

可以这样做:

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"
]