代码之家  ›  专栏  ›  技术社区  ›  Adam

typescript如何提示函数名

  •  -3
  • Adam  · 技术社区  · 7 年前

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

    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

    2 回复  |  直到 7 年前
        1
  •  0
  •   Josep    7 年前

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

    11手 foo bar 匿名函数和匿名函数是否没有名称…但是让我们想象一下你做了这样的事情:

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

    您期望什么样的接口 Sth 看起来像真的吗?为什么你关心函数的名称呢?

    根据你上次的评论,我 认为 你想要达到的目标是:

    interface Sth {
        caller: 'foo' | 'bar'
    }
    
        2
  •  0
  •   Adam    7 年前

    如果任何人正在寻找答案,为了实现上述目标,您需要创建一个由函数组成的对象,并使用它的键来键入提示类型使用 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

    推荐文章