无法转换为类型。 TypeScript TS2322 中的类型转换错误

问题描述 投票:0回答:0

我正在创建一个库,但无法正确输入。发生错误

TS2322: Type 'KeyValuePairOrNull' is not assignable to type '(keyof T extends keyof T["_dicts"] ? KeyValuePairOrNull : keyof T extends "_dicts" ? never : T[keyof T] extends (infer I)[] ? ObjectWithDict<...>[] : T[keyof T] extends object ? ObjectWithDict<...> : T[keyof T]) | undefined'.   Type 'null' is not assignable to type '(keyof T extends keyof T["_dicts"] ? KeyValuePairOrNull : keyof T extends "_dicts" ? never : T[keyof T] extends (infer I)[] ? ObjectWithDict<...>[] : T[keyof T] extends object ? ObjectWithDict<...> : T[keyof T]) | undefined'.

文件

clint.ts
`从 './types' 导入 {ObjWithDictMeta, ObjectWithDict, Entries, KeyValuePairOrNull}; 从'@company-libs/dictionary-client'导入{DictManager}; 从 'typeorm' 导入 { getMetadataArgsStorage };

// 主要 导出函数transformToDictInit(dictManager: DictManager) { 返回异步函数transformToDict(instance: T): Promise { 常量结果:ObjectWithDict = {}; const 关系 = getMetadataArgsStorage().filterRelations(instance.constructor.name).map(({ propertyName }) => propertyName);

const { _dicts } = instance;
const entries = Object.entries(instance) as Entries<T>;

for (const [propertyName, value] of entries) {
  if (propertyName === '_dicts') {
    continue;
  }

  if ( _dicts !== undefined && Object.hasOwn(_dicts, propertyName)) {
    const keyValue = await dictManager.getKeyValuePairByKey(value, _dicts[propertyName as string]);
    result[propertyName] = keyValue;
  }

  if (relations.includes(propertyName as string)) {
    if (!value) continue;

    if (Array.isArray(value)) {
      result[propertyName] = await Promise.all(value.map((v) => transformToDict(v)));
    }

    result[propertyName] = await transformToDict(value);
  }

  result[propertyName] = value;
}

return result; //as unknown as ObjectWithDict<T>;

}; }

 File
types.ts
 
导出接口 ObjWithDictMeta { new(...args: 任何[]): ObjWithDictMeta; [键:字符串]:任意; _dicts?: { [键: 字符串]: 字符串 }; } 导出接口KeyValue { 键:字符串; 值:字符串; } 导出声明类型 KeyValueMulti = KeyValue[]; 导出声明类型 KeyValuePairOrNull = KeyValue | KeyValueMulti |空;

export type ObjectWithDict<T extends ObjWithDictMeta> = {

[K in keyof T]?: K 扩展 keyof T['_dicts'] ?键值对或空 : K 扩展 '_dicts' ?绝不 : T[K] 扩展数组 ?对象与字典[] : T[K] 扩展对象 ?对象与字典 : T[K]; };

export type Entries<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T][];

`

javascript json typescript type-conversion
© www.soinside.com 2019 - 2024. All rights reserved.