英文:
Use typeof on inline function call
问题
type S = typeof identity("s"); // 无法实现,期望 ';'(1005)
type S2 = typeof identity("s"); // 无法实现,导出的类型别名 'S2' 使用了私有名称 ''
英文:
I'm just wondering if there is any way to call typeof directly on a function call, in the context of typescript, for example assigning to a type.
For example, suppose we have simple identity function
const identity =<T extends unknown>(x:T)=>x;
Then can get the type for 5 by first calling identity with 5 and then typeof on the result.
const five = identity(5);
type Five = typeof five
But say we want to directly get the type for "s"
type S = typeof identity("s") //cant do this. ';' expected.(1005)
type S2 = typeof (identity("s")) //cant do this. Exported type alias 'S2' has or is using private name ''.
Wonder if there is a way, not that it matters much, but some cases could be useful.
Also if not possible would be cool to know why, is typescript expecting some particular symbol after typeof?
Thanks
答案1
得分: 1
您可以使用实用工具ReturnType<Type>
和实例化表达式(应用泛型),如下所示:
const identity = <T extends unknown>(x: T) => x;
type S = ReturnType<typeof identity<"s">>;
//^? type S = "s"
英文:
You can use a combination of the utility ReturnType<Type>
and instantiation expression (applied generic), like this:
const identity = <T extends unknown>(x: T) => x;
type S = ReturnType<typeof identity<"s">>;
//^? type S = "s"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论