【问题标题】:Typescript how to hint function name打字稿如何提示函数名称
【发布时间】:2019-03-25 13:49:08
【问题描述】:

如何将函数名输入为字符串?这个伪代码说明了我的问题

const foo = () => null;
const bar = () => null;

interface Sth {
    caller: nameof foo | nameof bar
}

以上代码产生如下错误:

error TS2503: Cannot find namespace 'bar'.

这样就可以了: const x: Sth = { caller: 'foo' } 但这会出错: const y: Sth = { caller: 'y' }

Typescript playground

【问题讨论】:

  • 那些是匿名函数...匿名函数没有name 属性。我的意思是,这些是存储在名为foobar 的变量中的匿名函数,但函数本身没有名称。
  • 这个问题一团糟。不仅难懂意思,甚至连OK格式都没有,这是对读者的不尊重。你最好换个新的尝试,问新的,格式更好的问题。
  • 你有什么不明白的?如果您对格式有一些建议,请随时编辑问题。

标签: typescript


【解决方案1】:

我很难理解你在这里想要完成什么。

一方面foobar 是匿名函数,而匿名函数没有名称....但是让我们想象一下你做过这样的事情:

function foo(a: number) {
  return a;
}

function bar(x: number) {
  return x + 1;
}

您希望接口Sth 看起来像什么?为什么你完全关心函数的名称?

根据您的最后评论,我认为您要完成的是:

interface Sth {
    caller: 'foo' | 'bar'
}

【讨论】:

  • 如果没有函数名,caller 属性需要是一个字符串。我想将字符串选项限制为函数名称。这样下面会很好 const nar: Sth = { caller: 'foo' } 但下面会出错: const nar: Sth = { caller: 'xxx' }
  • @Adam 上下文在问题中会很有用。此外,很难看出您的答案对此有何帮助。在这种情况下,您可能还需要能够通过字符串名称访问该函数,因此拥有一个映射 const callers = { foo, bar } 可以让您使用 keyof callerscallers[caller]
  • 我更新了问题以闪现我想做得更好的地方。
  • @jonrsharpe 我尝试了你的建议,但我认为它不起作用:typescriptlang.org/play/…
  • @Adam 应该是keyof typeof callers; callers 是一个值,而不是一个类型。
【解决方案2】:

如果有人正在寻找答案,要实现上述目标,您需要创建一个由函数组成的对象,并使用它的键来键入提示类型,使用 keysof typeof

const foo = () => null;
const bar = () => null;

const functions = { foo, bar };

interface HasCallerType {
    caller: keyof typeof functions
}

const a: HasCallerType = {
    caller: 'foo'
}

使用此定义会出现以下错误:

const b: HasCallerType = {
    caller: 'meh'
}

这里是实际测试的链接:

Typescript playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2016-09-15
    相关资源
    最近更新 更多