7

I had a bug in my Angular 4 project where I had declared a variable:

debounce: 300;

instead of

debounce = 300;

So of course this.debounce was undefined before the fix.

Shouldn't Typescript give me an error in this case?

2
  • 1
    I'm a little bit confused, you declared a variable or is this part of an object?
    – MinusFour
    Nov 2, 2017 at 13:12
  • Part of a class like so: export class SearchComponent implements OnInit { model: any; searching = false; debounce: 300; } Nov 2, 2017 at 13:15

4 Answers 4

17

If you declare a variable with a type annotation of 300, that means not only is the type numeric, but only the value 300 is acceptable:

var debounce: 300;

You will get an error if you attempt to assign, say, 200:

debounce = 200;

Switch on strict null checks, and the compiler will catch this kind of problem (you meant to assign the value, not a type annotation):

var debounce: 200;

// Strict null checks tells you here that you have done something strange
var x = debounce;

In this case, when you try to use the variable, strict null checks points out you never assigned a value - thus telling you that you made an annotation, not an assignment.

9

You can basically pass (almost) anything as a value type to Typescript. So if you say:

class SomeClass {
  debounce: 300 | 500 | 700; 
  constructor() {
    this.debounce = 400;
  }
}

You will get a type error, since typescript is expecting the value for debounce to be 300, 500 or 700, not just any number. This means that you can be more specific about type annotations.

1

That line is correct because unintentionally you have used literal-types (for more information):

This example helps you to understand how literal-types is used for restricting variables to a finite set of possible values:

let zeroOrOne: 0 | 1;

zeroOrOne = 0;
// OK

zeroOrOne = 1; 
// OK

zeroOrOne = 2;
// Error: Type '2' is not assignable to type '0 | 1'
0

It's not a constant declaration. You have thought declared a variable and assigned a value implicitly typed. You are wrong. It's number type declaration that accepts specific values only.

debounce: 300;

and then assign it with

this.debounce = 300;

Typescript won't give you an error because it's syntactically correct, but runtime errors follows for undefined variables.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.