我正在为第三方js库创建一个TypeScript定义文件。其中一个方法允许使用options对象,而options对象的一个属性接受列表中的字符串:"collapse"、"expand"、"end-expand"和"none"。

我有一个接口的选项对象:

interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}

接口是否可以强制执行这一点,因此如果您包含带有brace_style属性的IOptions对象,它将只允许可接受列表中的字符串?


当前回答

Enum可能是最好的解决方案,但如果你的值是一个const对象的键,你不能改变它,语法将是

brace_style?: typeof BRACE_STYLES[keyof typeof BRACE_STYLES];

其中BRACE_STYLES是const对象的名称

其他回答

您可以创建由其他人指定的自定义类型。 我想补充一点,你也可以从对象const推断创建的类型:

export const braceStyles = {
  collapse: "collapse",
  expand: "expand",
  end-expand: "end-expand",
  none: "none"
}

export type braceStyle = typeof braceStyles[keyof typeof braceStyles]

export interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style?: bracestyle;
}

这样你就不必使用enum,你也可以在任何需要它们的地方使用对象属性,在那里它们的类型将是string,而不是enum.member

对象与枚举

TS提供了对特定字符串值的类型化,这些值称为字符串文字类型。

下面是一个如何使用它们的例子:

type style =  "collapse" | "expand" | "end-expand" | "none";

interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style1?:  "collapse" | "expand" | "end-expand" | "none";
  brace_style2?:  style;
}

// Ok
let obj1: IOptions = {brace_style1: 'collapse'};

// Compile time error:
// Type '"collapsessss"' is not assignable to type '"collapse" | "expand" | "end-expand" | "none" | undefined'.
let obj2: IOptions = {brace_style1: 'collapsessss'};

这在1.8版本中作为“字符串文字类型”发布

Typescript有什么新功能-字符串文字类型

本页示例:

interface AnimationOptions {
  deltaX: number;
  deltaY: number;
  easing: "ease-in" | "ease-out" | "ease-in-out";
}

在TypeScript 2.4以后,你可以使用字符串枚举

我喜欢这种方法,因为它避免了在多个地方使用相同的硬编码字符串的需要。

可以创建一个枚举,其中值为字符串

export enum VISIBILITY {
  PUBLISH = "publish",
  DRAFT = "draft"
}

这个枚举可以用作接口或类上的类型

export interface UserOptions  {
  visibility:  VISIBILITY 
}

Enum可能是最好的解决方案,但如果你的值是一个const对象的键,你不能改变它,语法将是

brace_style?: typeof BRACE_STYLES[keyof typeof BRACE_STYLES];

其中BRACE_STYLES是const对象的名称