使用typeof对内联函数调用

huangapple go评论60阅读模式
英文:

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>实例化表达式(应用泛型),如下所示:

TS Playground

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:

TS Playground

const identity = <T extends unknown>(x: T) => x;

type S = ReturnType<typeof identity<"s">>;
   //^? type S = "s"

huangapple
  • 本文由 发表于 2023年4月20日 04:52:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定