【问题标题】:How do I limit values to keys of an object?如何将值限制为对象的键?
【发布时间】:2017-09-11 03:41:12
【问题描述】:

假设我有以下内容:

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 中声明的键?

【问题讨论】:

  • 您不想将contentType 限制为ContentType 的值,而不是键吗?
  • 看起来你可以使用像this answer这样的查找类型...

标签: typescript


【解决方案1】:

您可以使用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,
};

【讨论】:

  • 我遇到的问题是我只是在到处重复这个值。虽然我强制要求只使用有效值,但我仍在重复它们。
  • @Omega 我已经用另一种方法更新了答案,您不必重复常量。
【解决方案2】:

这是我从 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 创建一个包含该对象键的类型。它是一个字符串联合类型。
  • 将您的字符串属性键入该联合类型,编译器将只允许这些字符串。

【讨论】:

  • 不敢相信我在野外偶然发现了著名的罗伯特彭纳!只是想说我是一个超级粉丝。
猜你喜欢
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
相关资源
最近更新 更多