在 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( (accumulator, current) => { return { …accumulator, …current }; }, {}, // 👈️ initial value );

    // 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

    1. 我们可以使用泛型来指定 `reduce()` 方法中的初始和返回值类型;<br />在上述例子中,变量`result`的类型为 `ReduceReturnType`;<br />且我们将 `ReduceReturnType` 中的属性设置为可选的,以确保编译不会出错,因为在 `reduce()` 中传递的初始值是一个空对象,不符合 `ReduceReturnType` 类型;<br />当然你也可以使用断言
    2. ```typescript
    3. const arr = [{ id: 1 }, { name: 'Alice' }, { salary: 100 }];
    4. type ReduceReturnType = {
    5. id: number; // 👈️ 👈️ 👈️ no longer optional
    6. name: string;
    7. salary: number;
    8. };
    9. const result = arr.reduce<ReduceReturnType>(
    10. (accumulator, current) => {
    11. return { ...accumulator, ...current };
    12. },
    13. {} as ReduceReturnType, // 👈️ 👈️ 👈️ Now using Type Assertion
    14. );
    15. // const result: ReduceReturnType
    16. console.log(result); // 👉️ {id: 1, name: 'Alice', salary: 100}
    17. console.log(result.id); // 👉️ 1
    18. console.log(result.name); // 👉️ "Alice"
    19. console.log(result.salary); // 👉️ 100