如何编写一种类型的数组,其值只是打字稿中对象键的一部分
how to write a type of array that value is only part of key of object in typescript
我有如下类型如何为数组编写类型,数组元素只能是键的一部分?
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
您可以使用 (keyof InputType)[]
:
const preferArray: (keyof InputType)[] = ['name', 'num', 'numRun'] // works
const preferArray1: (keyof InputType)[] = ['name', 'num', 'numRun', 'abc'] // error
我有如下类型如何为数组编写类型,数组元素只能是键的一部分?
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
您可以使用 (keyof InputType)[]
:
const preferArray: (keyof InputType)[] = ['name', 'num', 'numRun'] // works
const preferArray1: (keyof InputType)[] = ['name', 'num', 'numRun', 'abc'] // error