gpt4 book ai didi

TypeScript:如何为函数中的任何键键入对象剩余分布

转载 作者:行者123 更新时间:2023-12-04 08:06:46 26 4
gpt4 key购买 nike

我有一个接受一个对象并返回一个对象的函数。它返回整个传入对象,但添加了一个键。对象的形状是未知的,所以它可以有任何键,但它必须有 2 个确定的键。

const myFunction = ({
num1,
num2,
...rest
}: {
num1: number;
num2: number;
}) => ({
num1,
num2,
sum: num1 + num2,
...rest,
});

myFunction({ num1: 4, num2: 3, foo: 'bar' });
// or myFunction({ num1: 4, num2: 3, baz: 'qux', quux: 'quuz' });

这里 TypeScript 对 foo 大喊大叫。

Argument of type '{ num1: number; num2: number; foo: string; }' is not assignable to parameter of type '{ num1: number; num2: number; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ num1: number; num2: number; }

那是简化的例子。

这是我的实际功能以及我如何尝试使用 extends 解决它。

import type { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'utils/sessions';

const withAuthentication = async <
T extends {
request: NextApiRequest;
response: NextApiResponse;
},
K extends T
>({
request,
response,
...rest
}: T): Promise<
{
userSession: {
issuer: string;
publicAddress: string;
email: string;
};
} & K
> => {
const userSession = await getSession(request);

return { request, response, userSession, ...rest };
};

export default withAuthentication;

实际错误是这样的。

Type '{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is not assignable to type '{ userSession: { issuer: string; publicAddress: string; email: string; }; } & K'.
Type '{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is not assignable to type 'K'.
'{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '{ request: NextApiRequest; response: NextApiResponse<any>; }'.

如何输入这样的函数?

最佳答案

您可以使用 generics .

演示:https://repl.it/@chvolkmann/InternalFrugalCopyleft

interface MyArgs {
a: number
b: number
}

const doSomething = <A extends MyArgs>(args: A) => ({
...args,
sum: args.a + args.b
})

console.log(doSomething({ a: 10, b: 5, foo: 'bar' }))
// Output:
// { a: 10, b: 5, foo: 'bar', sum: 15 }

关于TypeScript:如何为函数中的任何键键入对象剩余分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66189050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com