typescript - 类型“T”上不存在属性“id”。(2339)打字稿泛型错误
问题描述
我有一个函数调用updateArrayOfObjects
它更新数组中的对象。我将一个泛型类型传递给这个函数,如下所示:
interface OtherIncomeSource {
id?: string;
incomeDescription?: string;
amount?: number;
}
const otherIncomes = [
{
id: "#6523-3244-3423-4343",
incomeDescription: "Rent",
amount: 100
},
{
id: "#6523-3244-3423-4343",
incomeDescription: "Commercial",
amount: undefined
}
]
const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
const newArrayOfObjects = arrayOfObjects.slice();
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
if(deleteObject) {
newArrayOfObjects.splice(index, 1);
} else {
if (index === -1) {
newArrayOfObjects.push(newObject);
} else {
newArrayOfObjects[index] = newObject;
}
}
return newArrayOfObjects
}
const newData = updateArrayOfObjects<OtherIncomeSource>(otherIncomes, {id: '1233', incomeDescription: 'agri', amount: 5000})
id
当访问说“类型'T'上不存在属性'id'。(2339)”时,我在下面提到的行中遇到错误:
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
以下是此问题的完整环境的 typescript playground 链接,此处错误以红色突出显示:Typescript Playground 中的示例
解决方案
您需要为您的泛型类型提供一个约束,如下所示:<T extends { id?: string }>
更新线路const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
至const updateArrayOfObjects = <T extends { id?: string }>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
推荐阅读
- android - 将标记(GPS)移动到下一条街道
- ios - 为银行账户信息创建令牌 Stripe
- javascript - 使用 Reactjs 和 Yii2 Api 上传文件
- google-bigquery - 为什么 Google-BigQuery 中没有加入修剪?
- sas - 如何将 2018 年 9 月 15 日 12:00 字符转换为日期时间?
- javascript - 如何在 JavaScript 中按 4 个属性排序
- database - Laravel 数据库自定义
- python - 如何使用openCV检测脸颊?
- google-apps-script - 如何总结每列中的值并通过谷歌表中的值总和对每列名称进行排名
- azure - 带有实体框架的 Service Fabric 应用程序?