Alexander Trauzzi
Alexander Trauzzi

Reputation: 7396

How do I limit values to keys of an object?

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

Answers (2)

Saravana
Saravana

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

Robert Penner
Robert Penner

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

  • Define a set of valid strings in an object literal.
  • Create a type that contains the keys of that object, using keyof. It's a string union type.
  • Type your string property to that union type, and the compiler will only allow those strings.

Upvotes: 11

Related Questions