0

Here is a bit of typescript:

let markdown = <HTMLTextAreaElement>document.getElementById(id);
let markdownoutput = <HTMLLabelElement>document.getElementById(output);

in above code, before select something using element by id, we are declaring the element type params.(<HTMLTextAreaElement>) it works fine. but what is the benefit are we getting from?

any one help me how the way typescript takes this and helps us?

thanks in advance.

user2024080
  • 1
  • 14
  • 56
  • 96

2 Answers2

2

Document.getElementById returns an interface of type HTMLElement. If this interface declares all properties and methods you're going to use in your code, there's no need to cast it with <>.

Specific types such as HTMLTextAreaElement have specific properties and methods that are not declared in any base interface (or base class). In order to be able to address/use them in your code, you need to cast them at compile-time (see https://stackoverflow.com/a/35362350/2358409).

uminder
  • 23,831
  • 5
  • 37
  • 72
1

One of the main ideas of generics is to have reusable code that can be relegated to a specific type when it's used (according to the generic type argument that is supplied). This way TypeScript will know what type to infer for the declared variable even if it's not added explicitly.

Kamen Minkov
  • 3,324
  • 1
  • 14
  • 21