TypeScript中typeof无法识别类成员方法的问题排查
问题场景
我定义了如下Record类:
declare class Record<Entries extends Dict = Dict, Key extends keyof Entries = keyof Entries, FieldLookup extends Dict<keyof Entries, number> = Dict<keyof Entries, number>> { keys: Key[]; length: number; private readonly _fields; private readonly _fieldLookup; constructor(keys: Key[], fields: any[], fieldLookup?: FieldLookup); forEach(visitor: Visitor<Entries, Key>): void; map<Value>(visitor: MapVisitor<Value, Entries, Key>): Value[]; entries(): IterableIterator<[string, any]>; values(): IterableIterator<Object>; [Symbol.iterator](): IterableIterator<Object>; toObject(): Entries; get<K extends keyof Entries = keyof Entries>(key: K): Entries[K]; get(n: number): any; has(key: Key | string | number): boolean; }
并在以下函数中使用该类:
export function toObjects( records: typeof neo4j.Record[], converters: Converters ) { const recordValues = records.map(record => { const out: string[] = [] record.forEach((val: {}) => out.push(itemIntToString(val, converters))) return out }) return recordValues }
尽管forEach方法已在Record类的实例上定义,但我收到错误:'Property 'forEach' does not exist on type 'typeof Record',同时还有多个类似的typeof相关错误。
补充说明:此处neo4j的定义如下:
declare const forExport: { Record: typeof Record, ... }
请问该问题的原因是什么?
问题原因
- 核心错误是类型声明混淆了类的构造函数类型与实例类型:你把
records的类型声明为typeof neo4j.Record[],其中typeof neo4j.Record指向的是Record类本身的构造函数类型,而不是类的实例类型。 - 遍历
records数组时,每个record变量的类型是构造函数typeof Record,而forEach是定义在Record实例上的方法,并非构造函数的静态方法,所以TypeScript会报错找不到该属性。 - 正确的数组类型应该是
neo4j.Record[],表示这是一个Record类的实例数组,而非构造函数数组。
内容的提问来源于stack exchange,提问作者François Richard
相关产品推荐
相关产品推荐

