24

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?

3
  • how about string[] ? Or are you looking for something more specific ? like maybe ['profiles', 'locations', 'change_history'] itself Commented Jul 30, 2019 at 3:55
  • looking for something specific. thx Commented Jul 30, 2019 at 3:57
  • Possible duplicate of TypeScript array to string literal type Commented Jul 30, 2019 at 4:27

3 Answers 3

34

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.

Sign up to request clarification or add additional context in comments.

Comments

14

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')[]
}

Comments

1

You could:

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

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

1 Comment

The values at runtime will be numbers! typescriptlang.org/docs/handbook/enums.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.