如何确保类型在数组内?

时间:2019-08-18 10:19:04

标签: typescript

如果我有一个像这样的数组:

const MyArray = [1,2,3,4,5,6]

和类似的功能

const MyArrayPrinter = (value) => console.log(value)

我是否可以确保function参数是在编译时位于数组内部的值?

例如:

 const MyArrayPrinter = (value: existsin MyArrayPrinter) => console.log(value)

2 个答案:

答案 0 :(得分:1)

有可能在编译时定义数组。您可以使用const assertion(将确保不扩展文字类型)并将其定义为只读元组,并查询/查找其值类型:

const myArray = [1, 2, 3, 4, 5, 6] as const;

type Value = typeof myArray[number]; // 1 | 2 | 3 | 4 | 5 | 6

const myArrayPrinter = (value: Value) => console.log(value)

myArrayPrinter(10) // Argument of type '10' is not assignable to parameter of type '1 | 2 | 3 | 4 | 5 | 6'.

Playground

答案 1 :(得分:0)

保持简单。您需要简单的代码,而不是您的幻想打字稿:

const myArray = [1,2,3,4,5,6];

const myArrayPrinter = (value) => {
  if (myArray.includes(value)) {
    console.log(value)
  }
}

TypeScript用于类型检查。值检查应在运行时进行:

  const myArray: Array<number> = [1,2,3,4,5,6];

  const myArrayPrinter = (value: number) => {
    if (myArray.includes(value)) {
      console.log(value)
    }
  }