通用对象参数作为其文字
Generic Object Param as Its Literal
我有一个接受通用对象的简单函数。 return 类型应与该对象相同,但缩小范围类似于 as const
断言的工作方式。
例如。以下应具有 return 类型的 { a: "first"; b: "second" }
而不是 { a: string; b: string }
:
myFn({ a: "first", b: "second" });
是否有一种机制可以指示类型检查器 myFn
的 return 类型是其第一个参数类型,缩小?
The return type should be the same as that object, but narrowed similar to how as const assertions work.
您可以通过将类型作为类型参数传递给函数来实现。
function myFn<T>(args): T {
// do stuff
return null;
}
const a = myFn<{ a: "first"; b: "second" }>(args);
type MyObj = { a: "first", b: "second" }
const a = myFn<MyObj>(args);
不幸的是,对象需要在编译时完全定义,因为类型在运行时不可用。
旧答案(曲解)
如果希望return类型与参数类型相同。然后就可以使用泛型类型参数了。
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);
我有一个接受通用对象的简单函数。 return 类型应与该对象相同,但缩小范围类似于 as const
断言的工作方式。
例如。以下应具有 return 类型的 { a: "first"; b: "second" }
而不是 { a: string; b: string }
:
myFn({ a: "first", b: "second" });
是否有一种机制可以指示类型检查器 myFn
的 return 类型是其第一个参数类型,缩小?
The return type should be the same as that object, but narrowed similar to how as const assertions work.
您可以通过将类型作为类型参数传递给函数来实现。
function myFn<T>(args): T {
// do stuff
return null;
}
const a = myFn<{ a: "first"; b: "second" }>(args);
type MyObj = { a: "first", b: "second" }
const a = myFn<MyObj>(args);
不幸的是,对象需要在编译时完全定义,因为类型在运行时不可用。
旧答案(曲解)
如果希望return类型与参数类型相同。然后就可以使用泛型类型参数了。
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);