0

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

1
  • That interface does not work for any of your examples. None of your variables have the name property that is required by the interface. Commented Mar 25, 2021 at 5:18

2 Answers 2

2

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']
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.