19

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?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
user1354934
  • 8,139
  • 15
  • 50
  • 80

3 Answers3

31

You basically have two options here:

const string enum

You can define a const enum the following way:

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

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.

karfau
  • 638
  • 4
  • 17
10

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')[]
}
Guilherme Samuel
  • 459
  • 6
  • 11
1

You could:

enum Relation {
    profiles: 'profiles', locations: 'locations', change_history: 'change_history'
}

interface IParams {
  id: number;
  relations: Relation[];
}
guijob
  • 4,413
  • 3
  • 20
  • 39
  • 1
    The values at runtime will be numbers! https://www.typescriptlang.org/docs/handbook/enums.html – karfau Jul 30 '19 at 04:03