Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Is there a way in typescript to declare type of this when defining an literal object

My case is that a javascript lib uses mixin method to create an object. Let's say it's a Car. In js, codes like

function Car( yourInjectObject ){
   Mixin(this, yourInjectObject)
}
Car.prototype.Run = function (){ ... }

Now in car.d.ts

class Car{
    Run(){ ... }
}

Now if I want to write my injectObject, I should always declare an interface

interface IMyInject extends Car{
    someVar:number
    Func1(){}
    Func2(){}
    //Func3(){} // no Func3 declare
}

let injectObject = {
    someVar: 0, 
    Func1(this: IMyInject ){
       this.Run() // ok
       this.Func2() // ok
       this.Func3() // type error, Func3 not declared
    },
    Func2() { // if I forgot add a this declare
       this.Run() // type error
       this.Func3() // type error, no declare of 
       this.Func1() // type error
    },
    Func3(this: IMyInject ){  //
       this.Run()   // ok
       this.Func1() // ok
       this.Func2() // ok
       this.Func3() // type error,
    },
}

let mycar = new Car(injectObject)

Is it possible to ease the codes, without predeclaring an interface. Suggest:

let myInject = MixIn<Car>{
    someVar:1,
    Func1(){ 
        this.someVar =2; 
        this.Run() 
        this.Func2()
    },
    Func2(){ 
        this.Run()
        this.Func1()
    }
}
let myCar = new Car(myInject)
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda