我们的代码在TypScript 4.7.4下可以正常编译和运行,但我们现在正在try 从TypScript 4.7.4升级到新版本.我们在4.8.4上编译时看到一个错误,而在4.7.4上编译时则不存在该错误.
我已将该错误隔离到其自己的小代码片段中.使用4.8.4(或任何更新的TypScript版本)进行编译时,我们会遇到这样的错误:
src/example2.ts:19:62 - error TS2345: Argument of type 'object' is not assignable to parameter of type 'Record<string, BasicValue>'.
Index signature for type 'string' is missing in type '{}'.
19 typeof value === 'object' && areFieldsValid(PFields, value, isValidPField);
~~~~~
这听起来类似于TypScript 4.8 - https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#unconstrained-generics-no-longer-assignable-to发布说明中对重大变更的描述,但并不相同
我们的可复制示例代码看起来像:
export interface PNode {
'text'?: string
}
export const PFields = ['text'];
export type DefinedBasicValue = number | boolean | string | Array<BasicValue> | {} | {
[key: string]: BasicValue
[key: number]: BasicValue
}
export type BasicValue = undefined | DefinedBasicValue
/**
* Take any object, value, undefined, or null, and determine if it is a PNode
*/
export const isPNode = (value?: {}): value is PNode =>
typeof value === 'object' && areFieldsValid(PFields, value, isValidPField)
export function areFieldsValid(fields: string[], value: Record<string, BasicValue>, ...validations: ((field: string, value: BasicValue) => boolean)[]): boolean {
return true
}
export const isValidPField = (field: string, value: BasicValue): boolean => true
错误与函数调用中的value
参数(第19行):areFieldsValid(PFields, value, isValidPField)
有关.
请有人帮助我们理解为什么这在TS 4.7中可以,但在新版本中却不行?另外,修复此类错误的"最佳"/"正确"方法是什么?我们希望避免"变通办法".
Playground using v4.7.4 with no error