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?
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.
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;
}
Array<T>
interface IParams {
id: number;
relations: Array<'profiles' | 'locations' | 'change_history'>
}
interface IParams {
id: number;
relations: ('profiles' | 'locations' | 'change_history')[]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With