2016-03-02 102 views
3

我想知道是否可以確定打字稿中的對象的類型。請考慮以下示例:Typeof/instanceof類型別名

type T = [number, boolean]; 

class B { 
    foo: T = [3, true]; 

    bar(): boolean { 
     return this.foo instanceof T; 
    } 
} 

typeof運算符似乎不是解決方案,instanceof也不是。

回答

2

簡短的回答

(幾乎)所有類型的信息被編譯後刪除,您不能使用instanceof運算符的操作數(T在你的例子),其在運行時不存在

龍答案

在打字稿的標識符可能屬於一個或多個以下組:類型命名空間。由於JavaScript是中的標識符,所以發出的是什麼內容。

因此,運行時操作員只能使用。因此,如果您想對foo的值進行運行時類型檢查,則需要自己努力工作。

請參見本節的更多信息:http://www.typescriptlang.org/Handbook#declaration-merging

3

爲了增加@vilcvane的回答是:typesinterfaces編譯過程中消失,但一些class信息仍然是可用的。因此,舉例來說,這不起作用:

interface MyInterface { } 

var myVar: MyInterface = { }; 

// compiler error: Cannot find name 'MyInterface' 
console.log(myVar instanceof MyInterface); 

但這:

class MyClass { } 

var myVar: MyClass = new MyClass(); 

// this will log "true" 
console.log(myVar instanceof MyClass); 

然而,要注意的是這種測試可能會產生誤導,甚至當你的代碼編譯很重要無錯誤:

class MyClass { } 

var myVar: MyClass = { }; 

// no compiler errors, but this logs "false" 
console.log(myVar instanceof MyClass); 

This makes sense if you look at how TypeScript is generating the output JavaScript in each of these examples

+0

類仍然存在,因爲一個類同時屬於* value *和* type *組。在第二個例子中,另一個關鍵是TypeScript根據類型的「形狀」進行類型檢查。儘管有關於GitHub上名義類型的討論:https://github.com/Microsoft/TypeScript/issues/202 – vilicvane