Home > Enterprise >  How can I convert an object constructor from javascript to work in typescript?
How can I convert an object constructor from javascript to work in typescript?

Time:02-04

I am learning TypeScript by converting a vanilla JS toto list project to React TypeScript.

In my old code, I had an object constructor Project that worked just fine:

function Project(title) {
  this.title = title;
  this.tasks = {};
}

As I try to implement this same constructor in TypeScript it seems like TS doesn't like my use of the word this. It underlines both this statements in red and hovering over it gives me the error:

'this' implicitly has type 'any' because it does not have a type annotation.

I tried adding types to it like so:

this.title: string = title;
title: string = title;

Both give me the error:

'string' only refers to a type, but is being used as a value here.

My main question is how would I write this same object constructor to work in TypeScript? What am I doing wrong with this? I have tried googling the problem but I don't see anything about this issue specifically on stack overflow or the typescript docs.

It looks like you can still make classes in typescript but I have tried to avoid them since 1) They aren't "real" in javascript, just syntactical sugar, and 2) I'd like to learn how to implement object constructors in TypeScript out of sheer intellectual curiosity, if possible.

CodePudding user response:

https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters

In a method or function definition, an initial parameter named this has special meaning in TypeScript. These parameters are erased during compilation:

// TypeScript input with 'this' parameter
function fn(this: SomeType, x: number) {
  /* ... */
}

CodePudding user response:

use class to solve the problem:

class Project {
  tasks: Record<string, unknown> = {}
  
  constructor(public title: string) {

  }
}
  • Related