在 ts 下在编写 reduce()
时可以使用泛型。例如 const result = arr.reduce<Recorde<string, string>>(myFunction, {});
- 在
reduce()
中,可以使用泛型来指定返回值(或者说初始值)的类型; ```typescript const arr = [{ id: 1 }, { name: ‘Alice’ }, { salary: 100 }];
type ReduceReturnType = { id?: number; name?: string; salary?: number; };
const result = arr.reduce
// const result: ReduceReturnType console.log(result); // 👉️ {id: 1, name: ‘Alice’, salary: 100}
console.log(result.id); // 👉️ 1 console.log(result.name); // 👉️ “Alice” console.log(result.salary); // 👉️ 100
我们可以使用泛型来指定 `reduce()` 方法中的初始和返回值类型;<br />在上述例子中,变量`result`的类型为 `ReduceReturnType`;<br />且我们将 `ReduceReturnType` 中的属性设置为可选的,以确保编译不会出错,因为在 `reduce()` 中传递的初始值是一个空对象,不符合 `ReduceReturnType` 类型;<br />当然你也可以使用断言
```typescript
const arr = [{ id: 1 }, { name: 'Alice' }, { salary: 100 }];
type ReduceReturnType = {
id: number; // 👈️ 👈️ 👈️ no longer optional
name: string;
salary: number;
};
const result = arr.reduce<ReduceReturnType>(
(accumulator, current) => {
return { ...accumulator, ...current };
},
{} as ReduceReturnType, // 👈️ 👈️ 👈️ Now using Type Assertion
);
// const result: ReduceReturnType
console.log(result); // 👉️ {id: 1, name: 'Alice', salary: 100}
console.log(result.id); // 👉️ 1
console.log(result.name); // 👉️ "Alice"
console.log(result.salary); // 👉️ 100