一般对象参数的字面意思

问题描述 投票:1回答:1

我有一个简单的函数,可以接受通用对象。返回类型应该与该对象相同,但缩小的范围类似于as const断言的工作方式。

例如。以下应具有{ a: "first"; b: "second" }而不是{ a: string; b: string }的返回类型:

myFn({ a: "first", b: "second" });

是否存在一种机制,我们可以通过该机制指示类型检查器将myFn的返回类型设为其第一个参数类型,缩小了?

typescript generics casting const narrowing
1个回答
0
投票

如果您希望返回类型与参数类型相同。然后,您可以使用通用类型参数。

function MyFunction<T>(argument1: T, anotherArg: number): T {
  // do stuff
}

// result will be of type User
const result = MyFunction<User>(user, 9);

在某些情况下,您可以做。

// user must be defined as type User above somewhere
const result = MyFunction(user, 9);
© www.soinside.com 2019 - 2024. All rights reserved.