假设我有以下内容:
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使用声明的键?
这是我从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)
keyof.这是一个字符串联合类型.| 归档时间: |
|
| 查看次数: |
1475 次 |
| 最近记录: |