How to require a specific string in TypeScript interface
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: "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 1:
This was released in version 1.8 as "string literal types"
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";
}
Solution 2:
Try this
export type ReadingTypes = 'some'|'variants'|'of'|'strings';
export interface IReadings {
param:ReadingTypes
}
Edit: Many thanks for upvotes, but, as time passed and me evolved as a developer :), now in most of the cases I wouldn't recommend this approach anymore. Yes it still valid but the point is the construction above is very similar to enum structure so why not use enum instead (advantages below):
export enum ReadingTypes {
Some = 'some',
Variants = 'variants',
Of = 'of',
Strings = 'strings',
}
export interface IReadings {
param: ReadingTypes
}
Advantages: (Yes, might be it is more like IMHO, I understand, but, nonetheless)
- It is more readable when you see it in the code, for example
if(item.reading === 'some') {
...
}
// vs
if(item.reading === ReadingTypes.Some) {
...
}
In first case when you read the code you could not catch, from the first glance, that .reading field can only contain few certain params, and not like, any string value.
- When you write the code you will have better assistance of your editor if you use enums - it is enough to remember name of enum and write it and it will show you all variants of enum. Yeah, with the first type ('some' | 'variants' ... ) it can do so too, but it does it less.. um.. eagerly