如何在TypeScript接口中要求特定的字符串

the*_*eks 98 typescript

我正在为第三方js库创建一个TypeScript定义文件.一项所述的方法允许对选择对象,并且选项对象的属性中的一个接收来自列表的字符串:"collapse","expand","end-expand",和"none".

我有一个options对象的接口:

interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}
Run Code Online (Sandbox Code Playgroud)

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

Rya*_*n Q 164

这在1.8版本中发布为"字符串文字类型"

Typescript中的新功能 - 字符串文字类型

页面示例:

interface AnimationOptions {
  deltaX: number;
  deltaY: number;
  easing: "ease-in" | "ease-out" | "ease-in-out";
}
Run Code Online (Sandbox Code Playgroud)

  • 它需要复制和粘贴带有字符串的行,无论你在app中需要将这种类型的字符串作为参数传递.如果你总是使用整个AnimationOptions解决方案似乎没问题,但对于只能传递'缓动'类型的用例,这是错误的.看Denis Khay回答,它好多了. (4认同)

小智 76

试试这个

export type ReadingTypes = 'some'|'variants'|'of'|'strings';

export interface IReadings {
   param:ReadingTypes
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该标记为正确,因为它允许在应用程序的任何位置重用创建的类型. (8认同)

Wil*_*een 15

TS 提供对特定字符串值的类型化,称为String 文字类型

以下是如何使用它们的示例:

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'};
Run Code Online (Sandbox Code Playgroud)


Dud*_*ude 14

另一种可能性是做类似的事情:

export type BraceStyleOptions = "collapse" | "expand" | "end-expand" | "none";

export interface IOptions{
  indent_size?: number;
  indent_char?: string;
  brace_style?: BraceStyleOptions;
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以在其他界面的任何地方重用您的选项。


Kub*_*oda 9

也许不完全是你想要的,但对你来说,它Enum似乎是一个完美的解决方案.

enum BraceStyle {Collapse, Expand, EndExpand, None}

interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style?: BraceStyle
}
Run Code Online (Sandbox Code Playgroud)

然而,枚举是基于数字的.这意味着在运行期间,例如BraceStyle.Collapse在这种情况下,实际值将为0.但是,您可以将它们与其他甚至非打字脚本一起使用,因为它们会编译为对象.这是BraceStyle编译和运行后的样子:

{
    0: "Collapse",
    1: "Expand",
    2: "EndExpand",
    3: "None",
    Collapse: 0,
    Expand: 1,
    EndExpand: 2,
    None: 3
}
Run Code Online (Sandbox Code Playgroud)

如果你想字符串时,可以使用静态成员类,描述在这里

  • `enum` 可以有字符串值(至少现在,不确定 2014 年是否可以)。`enum BraceStyle { Collapse = "Collapse", Expand = "Expand" }`。 (3认同)

Max*_*oll 9

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

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

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

export enum VISIBILITY {
  PUBLISH = "publish",
  DRAFT = "draft"
}
Run Code Online (Sandbox Code Playgroud)

然后可以将此枚举用作接口或类上的类型

export interface UserOptions  {
  visibility:  VISIBILITY 
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,全部大写会降低可读性 https://accessibility.huit.harvard.edu/design-readability (2认同)