Assign this to a method in typescript for intillisense

Viewed 43

Consider a method

function getName(){
   return this.name ;
}

now this method when called will have context of below class

class Person{
  name:string

  constructor(name){
     this.name=name;
  }
}

const person = new Person("Ujjwal");

getName.call(person);

the above implementation work but we don't get IntelliSense support or let's say I want to tightly couple the method with Person context.

Is there any way to achieve this?

NOTE: - I don't want to assign that getName method in class Person. getName will be always an independent method.

2 Answers

I was surprised to learn a few weeks ago this totally works:

type Person = {
  name: string;
}

function getName(this: Person) {
  return this.name;
}

const person : Person = {
  name: 'hi'
}

getName.bind(person);

It compiles to;

"use strict";
function getName() {
    return this.name;
}
const person = {
    name: 'hi'
};
getName.bind(person);

And yes IDE's should support completion for this.

Not quite sure what exactly you are trying to accomplish. Maybe if you provide more context there might be a better solution. For now, I guess, you can do something like this:

function getName<T extends NameInterface>(context:T):string{
   return context.name ;
}

interface NameInterface {
  name: string;
}

class Person implements NameInterface{
  name:string

  constructor(name: string){
     this.name=name;
  }
}

const person = new Person("Ujjwal");

let personName:string = getName(person);
console.log(personName);

Here I'm making your getName() function generic to be able to work with any object that has name property. To ensure type checking I introduced the NameInterface. Now any object that implements this interface can be passed into getName() function.

Related