If I have a type which looks like an array:
type names = ['Mike', 'Jeff', 'Ben'];
I can easily define another type which has values of items in names
:
type UserName = names[number]
For a function:
function hello(name: UserName) {
console.log(`Hello, ${name}!`)
}
I can only pass one of Mike
, Jeff
, Ben
to function hello
. If I give other values, like John
, it can't compile.
What if I don't have a type names
, but a const array names
?
const names = ['Mike', 'Jeff', 'Ben'];
type UserName = ???;
function hello(name: UserName) {
console.log(`Hello, ${name}!`)
}
hello('Mike');
Is it possible to define such a type UserName
?