V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
qiuyk
V2EX  ›  Node.js

问大家一个问题, TypeScript 中函数怎么以类而不是实例作为形参

  •  
  •   qiuyk · 2018-02-09 17:38:59 +08:00 · 4274 次点击
    这是一个创建于 2239 天前的主题,其中的信息可能已经有所发展或是发生改变。

    可能题目说得比较抽象,例如我们有个类:

    class Dog {
      private name: string;
      public constructor(name: string) {
        this.name = name;
      }
      public getName(): string {
        return this.name;
      }
    }
    

    然后我有一个函数,接受类作为参数,返回一个对象:

    function createDog(constructor: Dog): Dog {
       return new construtor('Teddy');
    }
    
    const teddy: Dog = createDog(Dog);
    

    但是大家知道这样编译是会报错的,因为createDog接受的是 Dog 实例。我不想用 any,想把我的类限定在 Dog,想问一下createDog(constructor: Dog)应该怎么写才能实现我的需求。

    6 条回复    2018-02-09 22:43:06 +08:00
    gucheen
        1
    gucheen  
       2018-02-09 17:44:34 +08:00   ❤️ 1
    createDog(constructor: typeof Dog)

    createDog(constructor: new(name: string) => Dog)

    或者建一个对应 Dog 的 interface
    sunjourney
        2
    sunjourney  
       2018-02-09 18:10:51 +08:00
    interface DogCreator {
    new(name: string): Dog
    }

    function createDog(constructor: DogCreator): Dog {
    return new constructor('Teddy');
    }

    你的单词写错了,看得我很难受。。。
    sunjourney
        3
    sunjourney  
       2018-02-09 18:12:42 +08:00
    另外,没必要这样写,perfer DI over FactorCreator
    sunjourney
        4
    sunjourney  
       2018-02-09 18:12:58 +08:00
    FactoryCreator
    VDimos
        5
    VDimos  
       2018-02-09 18:13:18 +08:00 via Android
    typescript 文档里面有提到的,在接口那一章。
    interface Test {
    new constructor():Dog
    }
    这样就行了
    qiuyk
        6
    qiuyk  
    OP
       2018-02-09 22:43:06 +08:00
    @sunjourney 哈哈 其实只是举个例子 也没想用工厂 只是这边实现有个形参需要传个构造函数而已 谢谢啦(本来想礼貌性道歉 结果你也拼错了 2333333 )
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3024 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 14:40 · PVG 22:40 · LAX 07:40 · JFK 10:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.