简体   繁体   English

此类型的TypeScript泛型

[英]TypeScript Generic of Type this

Why is TypeScript (2.1.0) complaining about the following code? 为什么TypeScript(2.1.0)抱怨以下代码?

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
  }
}

This line of your code (changed from self to this ): 您的代码的这一行(从self更改为this ):

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

Have two different meanings for the this keyword: this关键字有两种不同的含义:

  1. The actual reference to this at runtime ( this.request and this.url ) 在运行时this的实际引用( this.requestthis.url

  2. Specifying of the type of this for compilation ( new Request<this> ) 的类型的指定this编译( new Request<this>

You mixed the two meanings and that's why it does not work, if you want to use the self instead of this then you'll need to do use typeof : 您混合了两种含义,这就是为什么它不起作用的原因,如果要使用self而不是this则需要使用typeof

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM