返回值上的类型存在TypeScript问题
我得到了这个tslint错误:返回值上的类型存在TypeScript问题,typescript,amazon-dynamodb,typescript-typings,Typescript,Amazon Dynamodb,Typescript Typings,我得到了这个tslint错误: TS2322: Type 'ItemList | undefined' is not assignable to type 'Transaction<any, any, any>[]'. Type 'undefined' is not assignable to type 'Transaction<any, any, any>[]'. 交易类型如下: // I wont put the whole code, but those TF
TS2322: Type 'ItemList | undefined' is not assignable to type 'Transaction<any, any, any>[]'. Type 'undefined' is not assignable to type 'Transaction<any, any, any>[]'.
交易
类型如下:
// I wont put the whole code, but those TF, TV, TC are used on other types not listed here
export interface Transaction<TF, TV, TC> {
id: string;
commissions: Commissions;
createdAt: string;
}
//我不会把全部代码放在这里,但是那些TF、TV、TC用于这里没有列出的其他类型
导出接口事务{
id:字符串;
佣金:佣金;
createdAt:string;
}
因此,在函数的开头,我声明它将返回:Promise
因此,Items
实际上是一个Transaction
type对象数组
为什么会出现错误?正如您在中看到的那样,Items
属性可能未定义,因为您在tsconfig.json
中使用了strict
设置,这将导致错误。因此,一个简单的解决方法是始终返回一个数组:
export default async function getMyTransactions (
_root: any,
args: null,
): Promise<Array<Transaction<any, any, any>>> {
// ...
const { Items } = await DocumentClient.getInstance().query(query).promise();
return Items || [];
}
不幸的是,在查询数据时,dynamodb的类型没有任何泛型。我可以假设您必须执行以下操作才能使其正常工作:
export interface Transaction<TF, TV, TC> extends AttributeMap {
id: string;
commissions: Commissions;
createdAt: string;
}
导出接口事务扩展属性映射{
id:字符串;
佣金:佣金;
createdAt:string;
}
也许您必须专门键入cast,但不确定:
const { Items } = await DocumentClient.getInstance().query(query).promise();
return Items || [] as Transaction<any, any, any>[];
const{Items}=wait DocumentClient.getInstance().query(query.promise();
将项目| |[]作为交易[]返回;
项
是等待DocumentClient.getInstance().query(query).promise()的任何类型代码>解析为。该错误似乎表明其类型为ItemList | undefined
。嗯,是的,我在配置中有strict:true
。我尝试了这两种建议,但现在它给了我另一个错误:最后一行做了诀窍,谢谢Promise
和以数组形式返回项目代码>
Promise<Array<Transaction<any, any, any>> | undefined>
export interface Transaction<TF, TV, TC> extends AttributeMap {
id: string;
commissions: Commissions;
createdAt: string;
}
const { Items } = await DocumentClient.getInstance().query(query).promise();
return Items || [] as Transaction<any, any, any>[];