gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:03:39 25 4
gpt4 key购买 nike

假设我有以下内容:

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

最佳答案

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

关于typescript - 如何将值限制为对象的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43418993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com