typescript下面的操作遇到“不能给never赋值”的提示,该如何处理?

代码如下:

/** 对象类型 */
type TTestingRecordsItem = {
  age: number;
  cityCode: string;
  id: string;
  detResult: number;
  labNo: string;
  personName: string;
  sampleDate: string;
  sex: number;
  shardingKey: string;
  year: string;
  disease: number;
  prePositive: number;
};

/** 键值联合 */
type TKeyofRecordsItem = keyof TTestingRecordsItem;

// 对象实例
const record: TTestingRecordsItem = {} as TTestingRecordsItem;

// 键值实例
let key: TKeyofRecordsItem = '' as TKeyofRecordsItem;

// 值
let val: string | number = '';

key = 'disease'; // 此处会根据操作不同使用不同的字段值
val = '123'; // 此处会根据操作不同获得不同类型的值

setTimeout(() => {
  record[key] = key;

  // 目前的做法
  /* if (
    key === 'cityCode' ||
    key === 'id' ||
    key === 'labNo' ||
    key === 'personName' ||
    key === 'sampleDate' ||
    key === 'shardingKey' ||
    key === 'year'
  ) {
    record[key] = val as string;
  } else {
    record[key] = val as number;
  } */
}, 5000);

export {};

发现在此处提示如下:
typescript异常提示

运行是正常的,但ts提示还是不爽,不知道该怎用更优雅简洁的方法或设计消除这个提示呢?

阅读 1.4k
2 个回答

TTestingRecordsItem里面加个索引签名试试 [key: string]: any

你这名字起的我头晕

type aaa = {
  age: number;
  cityCode: string;
  id: string;
  detResult: number;
  labNo: string;
  personName: string;
  sampleDate: string;
  sex: number;
  shardingKey: string;
  year: string;
  disease: number;
  prePositive: number;
};


type K = keyof aaa;


const record: aaa = {} as aaa;


let key: K;


let val: aaa[K];

key = 'disease';
val = 23;

record[key] = val;

以上,是正确的写法

推荐问题
logo
Microsoft
子站问答
访问
宣传栏