【发布时间】:2021-05-17 05:16:03
【问题描述】:
我有一个函数,它接受一个对象并返回一个对象。它返回整个传入对象,但添加了一个键。对象的形状是未知的,所以它可以有任何键,但它必须有 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>; }'.
你怎么能键入这样的函数?
【问题讨论】:
-
不确定这是否是个好主意;
{ num1: number; num2: number; } & any作为参数类型。
标签: typescript typescript-typings spread-syntax typescript-types