如何将值限制为对象的键?

Ale*_*zzi 3 typescript

假设我有以下内容:

export const ContentType = {
    Json: "application/json",
    Urlencoded: "application/x-www-form-urlencoded",
    Multipart: "multipart/form-data",
};

export interface RequestOptions {
    contentType: string,
}

const defaultOptions: Partial<RequestOptions> = {
    contentType: ContentType.Json,
};
Run Code Online (Sandbox Code Playgroud)

我将如何限制,contentType以便只ContentType使用声明的键?

Rob*_*ner 8

这是我从TypeScript 2.1开始的首选方式:

export const contentTypes = {
    "application/json": true,
    "application/x-www-form-urlencoded": true,
    "multipart/form-data": true
};

type ContentType = keyof typeof contentTypes;

export interface RequestOptions {
    contentType: ContentType;
}

const defaultOptions: Partial<RequestOptions> = {
    contentType: "application/json",
};
Run Code Online (Sandbox Code Playgroud)

在TypeScript Playground中尝试一下

  • 在对象文字中定义一组有效字符串.
  • 使用包含该对象的键的类型keyof.这是一个字符串联合类型.
  • 键入您的字符串属性为该联合类型,编译器将只允许这些字符串.