DEV Community

Discussion on: Inventing your own HTML Elements to build a DOM game

Collapse
 
mapleleaf profile image
MapleLeaf • Edited

You can actually leave off a lot of typing information, and TS will infer it for you. For example:

class Person {
  name = 'defaultName' // no `: string` annotation
  age = 42 // no `: number` annotation

  // no `: string`
  info() {
    return `My name is ${this.name} and I am ${this.age} years old`
  }

  // no `: void`
  speak() {
    alert(this.info())
  }
}

// no `: Person`
const test = new Person()
Enter fullscreen mode Exit fullscreen mode

This is really great, because writing this way a lot of TS will end up just looking like normal JS in the end, while still reaping in all of the benefits of TS.

General rule I use is to turn on noImplicitAny (or the strict rule introduced in 2.2) in the tsconfig.json, then annotate anything that doesn't bypass the implicit any rule, usually function arguments.

That aside, great article! Really interesting way of doing things I never thought about.

Collapse
 
eerk profile image
eerk • Edited

Thanks! I added strict to tsconfig :) I still like to manually declare the type, it's more readable to me. It also tells other devs what your intention is with this variable.

const test:Person;
Enter fullscreen mode Exit fullscreen mode

Now we know that sooner or later test will be used to store a Person.

Collapse
 
mapleleaf profile image
MapleLeaf

Definitely helps readability, yeah. But any good modern editor will still tell you the type of the variable/function/method on hover as well.

Plus, const variables need an initial value anyway, but even if you use let instead, having an initial value helps to avoid those nasty undefined errors as well 😊