qiuyk
V2EX  ›  Node.js

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

  •  
  •   qiuyk · Feb 9, 2018 · 4772 views
    This topic created in 3013 days ago, the information mentioned may be changed or developed.

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

    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 replies    2018-02-09 22:43:06 +08:00
    gucheen
        1
    gucheen  
       Feb 9, 2018   ❤️ 1
    createDog(constructor: typeof Dog)

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

    或者建一个对应 Dog 的 interface
    sunjourney
        2
    sunjourney  
       Feb 9, 2018
    interface DogCreator {
    new(name: string): Dog
    }

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

    你的单词写错了,看得我很难受。。。
    sunjourney
        3
    sunjourney  
       Feb 9, 2018
    另外,没必要这样写,perfer DI over FactorCreator
    sunjourney
        4
    sunjourney  
       Feb 9, 2018
    FactoryCreator
    VDimos
        5
    VDimos  
       Feb 9, 2018 via Android
    typescript 文档里面有提到的,在接口那一章。
    interface Test {
    new constructor():Dog
    }
    这样就行了
    qiuyk
        6
    qiuyk  
    OP
       Feb 9, 2018
    @sunjourney 哈哈 其实只是举个例子 也没想用工厂 只是这边实现有个形参需要传个构造函数而已 谢谢啦(本来想礼貌性道歉 结果你也拼错了 2333333 )
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5634 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 73ms · UTC 07:22 · PVG 15:22 · LAX 00:22 · JFK 03:22
    ♥ Do have faith in what you're doing.