alice_morgan
alice_morgan

Reputation: 171

restrict array string value using typescript

I want an array that allow only for the value of 'john' and 'james', both are not required, I tried below interface:

interface User {
  name: ['john' | 'james']
}

but it doesn't work for

const user: User = ['john', 'james']

it work only

const user: User = ['john']
const user: User = ['james']

I think I missed something

Upvotes: 0

Views: 1494

Answers (2)

ricardo-dlc
ricardo-dlc

Reputation: 486

If the use of an interface is not mandatory, you can take advantage of union types:

type User = 'john' | 'james';

const user1:User[] = ['john', 'james', 'jane'];
// ----------------------------------> ~~~~~~
//                                     Type '"jane"' is not assignable to type 'User'.(2322)

const user2:User[] = ['john', 'james', 'james']; // No errors

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97162

You have typed an array with exactly one element that can either be john or james. If you want to allow multiple elements, you will need to do:

interface User {
  name: ('john' | 'james')[]
}

Now all the following are valid:

const u1: User = {
  name: ['john']
};

const u2: User = {
  name: ['james']
};

const u3: User = {
  name: ['john', 'james']
};

Upvotes: 2

Related Questions