Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript array of specific string values

Tags:

typescript

I have an array

const relations = ['profiles', 'locations', 'change_history']

If I want to create an interface like

interface IParams {
  id: number;
  relations: []string; // how to make this an array of those relations above?
}

How can I do that?

like image 806
user1354934 Avatar asked Jul 30 '19 03:07

user1354934


Video Answer


2 Answers

You basically have two options here:

const string enum

  • https://www.typescriptlang.org/docs/handbook/enums.html#string-enums (for having the string values present for checks at runtime)
  • https://www.typescriptlang.org/docs/handbook/enums.html#const-enums (to avoid some overhead concerning enums and replacing references to them in your code with the string literals)

You can define a const enum the following way:

const enum Relation {
  profiles = 'profiles', 
  locations = 'locations', 
  change_history = 'change_history'
}

string literal types

  • https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
type Relation = 'profiles' | 'locations' | 'change_history';

and like @guijob already pointed out this would be your interface (in both cases):

interface IParams {
  id: number;
  relations: Relation[];
}

Of course you could also inline this string literal type definition

relations: ('profiles' | 'locations' | 'change_history')[];

But be aware that values are not checked at runtime!

So if you add data from a resource that is not checked at compile time (like an API or user input) there is no guarantee for only those values being present.

like image 171
karfau Avatar answered Oct 26 '22 16:10

karfau


You can use as const assertions to effortless type "relations"

const relations = ['profiles', 'locations', 'change_history'] as const

interface IParams {
  id: number;
  relations: typeof relations;
}

As an alternative, you can use Array<T>

interface IParams {
  id: number;
  relations: Array<'profiles' | 'locations' | 'change_history'>
}

Or if you prefer the other syntax

interface IParams {
  id: number;
  relations: ('profiles' | 'locations' | 'change_history')[]
}
like image 24
Guilherme Samuel Avatar answered Oct 26 '22 16:10

Guilherme Samuel