snippettypescriptCritical
How to require a specific string in TypeScript interface
Viewed 0 times
typescripthowinterfacerequirespecificstring
Problem
I'm creating a TypeScript definition file for a 3rd party js library. One of the methods allows for an options object, and one of the properties of the options object accepts a string from the list:
I have an interface for the options object:
Can the interface enforce this, so if you include an
"collapse", "expand", "end-expand", and "none".I have an interface for the options object:
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}Can the interface enforce this, so if you include an
IOptions object with the brace_style property, it will only allow a string that is in the acceptable list?Solution
This was released in version 1.8 as "string literal types"
What's New in Typescript - String Literal Types
Example from the page:
What's New in Typescript - String Literal Types
Example from the page:
interface AnimationOptions {
deltaX: number;
deltaY: number;
easing: "ease-in" | "ease-out" | "ease-in-out";
}Code Snippets
interface AnimationOptions {
deltaX: number;
deltaY: number;
easing: "ease-in" | "ease-out" | "ease-in-out";
}Context
Stack Overflow Q#26855423, score: 476
Revisions (0)
No revisions yet.