Reputation: 7396
Assume I have the following:
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,
};
How would I go about restricting contentType
so that only keys declared in ContentType
are used?
Upvotes: 3
Views: 3581
Reputation: 40544
You can use string literal types. Instead of typing contentType
as string
, type it as a literal type of possible values.
export interface RequestOptions {
contentType: "application/json" | "multipart/form-data" | "multipart/form-data:"
}
To avoid repeating your constants you can declare them separately and type contentType
as 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,
};
Upvotes: 1
Reputation: 6398
This is my preferred way as of 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
. It's a string union type.Upvotes: 11