TS2345

error TS2345: Argument of type ‘x‘ is not assignable to parameter of type ‘y‘.

1
2
3
4
5
6
error TS2345: Argument of type '(records: T[]) => void' is not assignable to parameter of type '(value: [{}, {}, {}, {}, > {}, {}, {}, {}, {}, {}]) => void | PromiseLike<void>'.
Types of parameters 'records' and 'value' are incompatible.
Type '[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]' is not assignable to type 'T[]'.
Types of property 'pop' are incompatible.
Type '() => {}' is not assignable to type '() => T'.
Type '{}' is not assignable to type 'T'.

Bad Code ❌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
readAll<T>(tableName: string): Promise<T[]> {
return this.resolvePath(tableName).then(directory => {
return new Promise<T[]>((resolve, reject) => {
fs.readdir(directory, (error, files) => {
if (error) {
reject(error);
} else {
const recordNames = files.map(file => path.basename(file, path.extname(file)));
const promises = recordNames.map(primaryKey => this.read(tableName, primaryKey));
Promise.all(promises).then((records: T[]) => resolve(records));
}
});
});
});
}

Fixed Code ✔️

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
readAll<T>(tableName: string): Promise<T[]> {
return this.resolvePath(tableName).then(directory => {
return new Promise<T[]>((resolve, reject) => {
fs.readdir(directory, (error, files) => {
if (error) {
reject(error);
} else {
const recordNames = files.map(file => path.basename(file, path.extname(file)));
const promises: Array<Promise<T>> = recordNames.map(primaryKey => this.read(tableName, primaryKey));
Promise.all(promises).then((records: T[]) => resolve(records));
}
});
});
});
}