2014-11-06 222 views
0

我沿着這些路線的打字稿應用的東西我建立什麼類型是構造函數?

class Thing { 
    static ReleventInfo: string 
} 
class Foo extends Thing { } 
class Bar extends Thing { } 
class Baz extends Thing { } 

var things = { 
    foo: Foo, 
    bar: Bar, 
    baz: Baz, 
} 


function FooPlease(): Foo { 
    return new things.foo; 
} 

function ThingPlease(thing: string): Thing { 
    if (!things[thing]) 
     return null; 
    var ctor = things[thing]; 
    // ctor now has type of 'any', can't access 'ReventInfo' nicely. 
    var newThing = new ctor(); 
    // newThing now has type of 'any' 
    return newThing; 
} 

其中工作,但打字稿(和智能)失去跟蹤什麼類型ctor因此newthing是,這是因爲有問題我希望訪問它們的靜態屬性和對象方法。 我應該說什麼類型的var是?智能感知無助地提供這樣的信息: (var) things = { foo: typeof(Foo) }(class) Foo

回答

1

因爲打字稿不知道可以傳遞給ThingPlease什麼可能的字符串不能確定類型。

你需要使用一個類型斷言給它一個暗示:

var ctor = <typeof Thing>things[thing]; 

完整的示例如下:

class Thing { 
    static ReleventInfo: string 
} 

class Foo extends Thing { } 
class Bar extends Thing { } 
class Baz extends Thing { } 

var things = { 
    foo: Foo, 
    bar: Bar, 
    baz: Baz, 
} 


function FooPlease(): Foo { 
    return new things.foo; 
} 

function ThingPlease(thing: string): Thing { 
    if (!things[thing]) { 
     return null; 
    } 

    // ctor is `typeof Thing` 
    var ctor = <typeof Thing>things[thing]; 

    // newThing is `Thing` 
    var newThing = new ctor(); 

    return newThing; 
} 
+1

整潔,我沒有意識到'typeof Thing'是一個實際的類型說明符。我認爲這是Intellisense試圖幫助。 (雖然想到它 - 顯然是) – 2014-11-06 10:57:53

1

基於史蒂夫的答案,我意識到,我可以定義與地圖的地圖鍵入{ [thingType: string]: typeof Thing }而不是隱含它 - 這導致所有訪問返回一個typeof Thing沒有演員!

class Thing { 
    static ReleventInfo: string 
} 
class Foo extends Thing { } 
class Bar extends Thing { } 
class Baz extends Thing { } 

var things: { [thingType: string]: typeof Thing } = { 
    foo: Foo, 
    bar: Bar, 
    baz: Baz, 
} 


function FooPlease(): Foo { 
    return new things.foo; 
} 

function ThingPlease(thing: string): Thing { 
    if (!things[thing]) 
     return null; 
    var ctor = things[thing]; 
    var newThing = new ctor(); 
    return newThing; 
} 
相關問題