Javascript 使用typescript限制数组字符串值

Javascript 使用typescript限制数组字符串值,javascript,typescript,Javascript,Typescript,我想要一个只允许'john'和'james'值的数组,这两个值都不是必需的,我尝试了以下界面: interface User { name: ['john' | 'james'] } 但这对我来说不起作用 const user: User = ['john', 'james'] 它只起作用 const user: User = ['john'] const user: User = ['james'] 我想我遗漏了什么您键入了一个数组,其中正好有一个元素可以是john或james。如果

我想要一个只允许'john'和'james'值的数组,这两个值都不是必需的,我尝试了以下界面:

interface User {
  name: ['john' | 'james']
}
但这对我来说不起作用

const user: User = ['john', 'james']
它只起作用

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

我想我遗漏了什么

您键入了一个数组,其中正好有一个元素可以是
john
james
。如果要允许多个元素,则需要执行以下操作:

interface User {
  name: ('john' | 'james')[]
}
现在,以下各项均有效:

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

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

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

您键入了一个数组,其中正好有一个元素可以是
john
james
。如果要允许多个元素,则需要执行以下操作:

interface User {
  name: ('john' | 'james')[]
}
现在,以下各项均有效:

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

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

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

如果接口的使用不是强制性的,您可以利用:

type User='john'|'james';
constuser1:User[]=['john','james','jane'];
// ----------------------------------> ~~~~~~
//类型“jane”不可分配给类型“User”。(2322)
constuser2:User[]=['john','james','james'];//没有错误

如果不强制使用接口,您可以利用:

type User='john'|'james';
constuser1:User[]=['john','james','jane'];
// ----------------------------------> ~~~~~~
//类型“jane”不可分配给类型“User”。(2322)
constuser2:User[]=['john','james','james'];//没有错误

该接口不适用于您的任何示例。没有一个变量具有接口所需的
name
属性。该接口不适用于任何示例。没有一个变量具有接口所需的
名称
属性。