【问题标题】:how to write a type of array that value is only part of key of object in typescript如何编写一种数组类型,该数组的值只是打字稿中对象键的一部分
【发布时间】:2021-10-06 08:33:50
【问题描述】:

我有一个像下面这样的类型,如何为数组编写一个类型,数组的元素只能是键的一部分?

type InputType = {
  name: string;
  phone: string;
  num: number;
  numRun: number;
  numEdit: number;
  posiRun: number;
  posiEdit: number;
}

const preferArray = ['name', 'num', 'numRun']
const preferArray = ['name', 'num', 'numRun', 'abc'] // should complain the error because abc is not part of key from InputType

【问题讨论】:

    标签: typescript typescript-typings typescript2.0


    【解决方案1】:

    你可以使用(keyof InputType)[]:

    const preferArray: (keyof InputType)[] = ['name', 'num', 'numRun'] // works
    const preferArray1: (keyof InputType)[] = ['name', 'num', 'numRun', 'abc'] // error
    

    playground

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多