1

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.

4

2 Answers 2

2

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) {
  /* ... */
}
Sign up to request clarification or add additional context in comments.

Comments

1

use class to solve the problem:

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

  }
}

3 Comments

Thank you I appreciate it but as per my question I was also asking if it were possible to solve this without using class. Just honestly curious.
@manski it is possible but why don't you want to use class in my experience it is about several times faster than using function and this
honestly just intellectual curiosity. I have my answer though, I went ahead and just committed to using class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.