2016-07-30 3 views
0

TypeScript(2.1.0)が次のコードについて不平を言っているのはなぜですか?TypeScript Generic of this

import Request from "../request/request.ts"; 
export default class Machine{ 
    private id: number; 
    private url:string; 
    private make:string; 
    private model:string; 
    private request:any; 
    constructor(){ 
    var self = this; 
    this.request = new Request<self>(this.url); //cannot find name self 
    } 
} 

答えて

2

あなたのコードのこの行(thisselfから変更):

  1. 実行時にthisへの実際の参照:

    this.request = new Request<this>(this.url); 
    

    thisキーワードに2つの異なる意味を持ちます(this.requestおよびthis.url

  2. コンパイル用thisの種類の指定(new Request<this>

あなたは2つの意味が混合され、それが動作しない理由です、あなたがself代わりのthisを使用したい場合は、あなたがする必要があります使用するtypeof

this.request = new Request<typeof self>(this.url); 
+0

コンパイラが自己のタイプを推測しないバグですか?それはしてはならない理由はありますか? –

+1

いいえ、それはバグではなく、 'self'は変数ですが、ジェネリック型として置くのは型でなければならないので動作しませんが、' typeof self'は動作します。 –

関連する問題