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

时间:2017-04-14 20:45:07

标签: 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,
};

如何限制contentType,以便只使用ContentType中声明的密钥?

2 个答案:

答案 0 :(得分:7)

这是我从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",
};

Try it in TypeScript Playground

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

答案 1 :(得分:0)

您可以使用string literal types。不要将contentType键入string,而是将其输入为可能值的文字类型。

export interface RequestOptions {
    contentType: "application/json" | "multipart/form-data" | "multipart/form-data:"
}

为避免重复常量,您可以单独声明它们,并将contentType键入typeof ConstantString

export const ContentTypeJson = "application/json";
export const ContentTypeUrlencoded = "application/x-www-form-urlencoded";
export const ContentTypeMultipart = "multipart/form-data";


export interface RequestOptions {
    contentType: typeof ContentTypeJson| typeof ContentTypeUrlencoded | typeof ContentTypeMultipart,
}

const defaultOptions: Partial<RequestOptions> = {
    contentType: ContentTypeJson,
};