假设我有以下内容:
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
中声明的密钥?
答案 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,
};