当前位置:网站首页>Typescript type system

Typescript type system

2022-06-24 01:33:00 HoneyMoose

in the light of JavaScript The above question , Smart students think we'll give JavaScript Add a type , and Java equally , Be able to define the type of variable , The idea is TypeScript The type of system , To a great extent JavaScript The confusion caused by .

from TypeScript Your name can be seen ,「 type 」 Is its core feature ,TypeScript It is also mainly committed to solving JavaScript The type of confusion problem .

TypeScript Is a static type

The type system follows 「 The timing of the type check 」 To classify , It can be divided into the following 2 Kind of

  • Dynamic type
  • Static type

Dynamic type This means that type checking is performed only at run time , The wrong type of language often leads to runtime errors . JavaScript It's an interpretive language , There is no compile phase ( This is another target Java Students often make complaints about their places. ), So it's a dynamic type , The following code will only report an error at run time :

let foo = 1;
foo.split(' ');
// Uncaught TypeError: foo.split is not a function
//  The runtime will report an error (foo.split  Not a function ), Caused during operation  bug.
//  Open your browser  F12  Look at how many mistakes there are, and you'll see .

Static type It means that the type of each variable can be determined at the compilation stage , The wrong type of language often leads to grammatical errors .TypeScript Before running, you need to compile to JavaScript, Type checking is done at the compile stage , therefore  TypeScript Is a static type , This paragraph TypeScript The code will report an error at the compilation stage :

let foo = 1;
foo.split(' ');
// Property 'split' does not exist on type 'number'.
//  Error will be reported at compile time ( The numbers don't have  split  Method ), Unable to compile 

You may be surprised , This paragraph TypeScript The code looks like JavaScript There's no difference .

you 're right ! Most of the JavaScript The code needs only a small amount of modification ( Or no modification at all ) It becomes TypeScript Code , Thanks to TypeScript Powerful [ type inference ][], Even if you don't declare variables manually  foo  The type of , It can also automatically infer that it is a  number  type .

complete TypeScript The code looks like this :

let foo: number = 1;
foo.split(' ');
// Property 'split' does not exist on type 'number'.
//  Error will be reported at compile time ( The numbers don't have  split  Method ), Unable to compile 

TypeScript It is hoped that this can be enhanced through the above configuration JavaScript The function of .

https://www.ossez.com/t/typescript/13809

原网站

版权声明
本文为[HoneyMoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211117102012695V.html

随机推荐