推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
wktrf

Typescript 类型里面类的表达方式

  •  
  •   wktrf · Oct 24, 2018 · 3096 views
    This topic created in 2788 days ago, the information mentioned may be changed or developed.

    我看到文档里面写了两种:

    function create<T>(c: new() => T):T{
    	return new c()
    }
    

    function create<T>(c: {new(): T}):T{
    	return new c()
    }
    

    这两种,new() => T{new(): T}又什么区别?

    第二种的{new(): T}改成{new(): T, a: number}这个该怎么传递参数呢?

    3 replies    2018-10-24 16:21:46 +08:00
    beny2mor
        1
    beny2mor  
       Oct 24, 2018
    第一种是方法签名,表示 c 可以使用 new c()调用

    第二种应该是类要实现{new(): T}这个接口
    noe132
        2
    noe132  
       Oct 24, 2018
    create2 基本等价于 newable interface
    interface C2<T> {
    new (): T
    }
    const create2 = <T>(c: C2<T>): T => new c()

    这两者表达的意思是相等的

    let func = create1
    func = create2
    不会报错

    如果还希望加其他限制就得使用 create2 这种方式。
    Pastsong
        3
    Pastsong  
       Oct 24, 2018
    用 class 关键字吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3239 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 02:51 · PVG 10:51 · LAX 19:51 · JFK 22:51
    ♥ Do have faith in what you're doing.