You can actually leave off a lot of typing information, and TS will infer it for you. For example:
classPerson{name='defaultName'// no `: string` annotationage=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`consttest=newPerson()
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.
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;
Now we know that sooner or later test will be used to store a Person.
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 😊
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You can actually leave off a lot of typing information, and TS will infer it for you. For example:
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 thestrict
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.
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.Now we know that sooner or later
test
will be used to store aPerson
.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 😊