In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "what are the basic grammars of Typescript". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "what are the basic grammars of Typescript?"
I. what is ts?
First, strong typing does not allow arbitrary implicit type conversions, while weak typing is allowed. JavaScript is a classic weakly typed language. Typescript can be said to be a superset of JavaScript, adding a lot of syntax features on the basis of JS, so that types can no longer be converted at will and can greatly reduce errors in the development phase.
two。 Basic grammar
1. Declare the original data type
Specify a keyword after the variable to indicate what type it can only be.
String type:
Const a: string = 'auroras'
Number type:
Const b: number = 666 / / including NAN Infinity
Boolean type:
Const c: boolean = true
Null type:
Const d: null = null
Undefined type:
Const e: undefined = undefined
Symbol type:
Const h: symbol = Symbol () 2. Declare the Object type
First, the object type can specify not only objects, but also arrays or functions:
Const foo1: object = {}; const foo2: object = []; const foo3: object = function () {}
If you only want to specify it as an object, you should declare the type in advance as follows:
Const obj: {name: string,age: number} = {name: 'aurora borealis', age:18} 2.1 declare array types
You can specify the declaration Array and by specifying the element type, such as an array that declares that all elements are numbers:
Const arr: Array = [1, 2, 2, 3]
The second way is as follows, which also specifies an array that declares that all elements are numbers:
Const arr: number [] = [1J 2je 3] 2.2 declare tuple types
It is necessary to specify the type of each element in the array in advance, which corresponds strictly one to one:
Const tuple: [number,string,boolean] = [666 Magneto auraroscopyric true] 3. Declare enumerated types
Declare an enumerated type through the keyword enum, such as:
Enum Status {pedding = 1, resolve = 2, reject ='3'} / / visit console.log (Status.pedding)
If none is written, the default value is incremented from 0. If the first element is a character type, all values must be defined. If the first element is specified as a number and the subsequent element does not write a value, the value is the result of the positional increase in the value of the first element.
4. Function parameters and return types
Function declarative:
Specify the parameter type passed in to the function and the return value type. When calling, the number and type of parameters passed must be the same:
Each parameter type is specified in parentheses, and the type of return value is specified to the right of the parentheses.
Function fun (name:string,age:number): string {return 'sss'} fun (' auroras',18)
If the passed parameter is not sure whether it is passed or not, you can add a'?'to the parameter. Indicates that it is optional:
Function fun (name:string,age?:number): string {return 'sss'} fun (' auroras')
Or add a default value to the parameter, which becomes optional:
Function fun (name:string,age:number=666): string {return 'sss'} fun (' auroras')
If the number of parameters is uncertain, it can be represented by an extension operator plus a deconstruction assignment, of course, if it is consistent with the specified type:
Function fun (name:string,age:number=666,...res:number []): string {return 'sss'} fun (' auroras',1,2,3)
Function expression:
Const fun2: (name:string,age:number) = > string = function (name:string,age:number) {return 'sss'}
We'll talk more about it when you define the interface.
5. Any type
By specifying the any keyword to represent any type, like the original js, you can assign different types of values at will:
Let num:any = 1 ~ (th) num ='a ~ num = true;6. Type assertion
Type assertions explicitly tell typescript that the variable is of some type, 100% certain. In some cases, you don't need typescript to infer for yourself what types of scenarios are not clearly defined or changeable.
You can assert that it is a certain type through the as+ type:
Const res = 1th Const num = res as number
You can also make formal assertions (not recommended):
Const res = 1 world Const num = res7. Basic use of interface
Interface can be understood as a specification, a contract. You can constrain which members should be in an object and what those members are like.
A Post interface is defined through interface, which is an object and the rule is that there is a name attribute of type string,age and a type of number.
Interface Post {name:string; age:number}
Then, for example, if there is a function printPost whose parameter post uses the rules of the Post interface we defined, the data that conforms to the rules of the Post interface should be passed in when calling this function.
Interface Post {name:string; age:number} function printPost (post: Post) {console.log (post.name); console.log (post.age);} printPost ({name:'asd',age:666})
Of course, some parameters may be optional when passing parameters to the function, so we can also define optional members for the interface and add a'? 'after the attribute. Specify optional members:
Interface Post {name:string; age:number; sex?:string;} const auroras: Post = {name:'asd', age: 18}
If you modify a member with readonly, the member property cannot be modified after initialization:
Interface Post {name:string; age:number; sex?:string; readonly like:string} const auroras: Post = {name:'asd', age: 18, like: 'natrue'} auroras.name =' aaaa';// error protection auroras.like = 'wind'
If you are not sure about the member attribute name, you can declare a dynamic member by specifying the member name type and the type of the member value, such as:
Interface Post {[prop:string]: string} const auroras: Post = {name:'asd', like: 'natrue'} 8. Basic use of class
Describe the abstract characteristics of a class of concrete things. Ts enhances the syntax of the class class in es6.
First of all, the properties of the class must be declared in advance before they are used:
Class Person {name:string; age:number; constructor (name:string,age:number) {this.name = name; this.age = age;} sayHi (msg:string): void {console.log (`hi,$ {msg}, I am ${this.name} `);}} 9. Access modifier for the class
Private modifies private properties and can only be accessed within the class. Public decorates common properties (default)
It can also be accessed externally:
Class Person {public name:string; private age:number; constructor (name:string,age:number) {this.name = name; this.age = age;} sayHi (msg:string): void {console.log (`hi,$ {msg}, I am ${this.name} `); console.log (this.age);} const jack = new Person ('jack',20) / / the public property of the Person class can access console.log (jack.name); / / the private property of the Person class cannot access console.log (jack.age); the protected is decorated as protected and inaccessible externally. But the difference with private is that inherited subclasses are accessible. Class Person {public name:string; private age:number; / / protected protected gender: boolean; constructor (name:string,age:number) {this.name = name; this.age = age; this.gender = true;} sayHi (msg:string): void {console.log (`hi,$ {msg}, I am ${this.name} `); console.log (this.age) }} class children extends Person {constructor (name:string,age:number) {super (name,age,); / / can visit console.log (this.gender);}} 10. Class read-only property
Setting readonly to a property is read-only and cannot be modified after initialization.
Class Person {public name:string; private age:number; / / readonly protected readonly gender: boolean; constructor (name:string,age:number) {this.name = name; this.age = age; this.gender = true;} sayHi (msg:string): void {console.log (`hi,$ {msg}, I am ${this.name} `); console.log (this.age);}} 11. Class and interface
Some classes have some common characteristics, which can be abstracted into interfaces.
For example, Person class and Animal class, although different, but people and animals can eat and walk, these common characteristics can be defined by the interface. The last feature defines an interface.
/ / Food interface interface Eat {eat (food:string): void} / / Walking interface interface Run {run (behavior:string): void} / / Human class People implements Eat,Run {eat (food:string) {console.log (`eat ${food} `on the dinner table);} run (behavior:string) {console.log (`standing ${behavior}`) }} / / Animal class Animal implements Eat,Run {eat (food:string) {console.log (`eat ${food} `on the ground);} run (behavior:string) {console.log (`crawling ${behavior}`);}} 12. Abstract class
The constraint subclass must have some members, somewhat similar to the interface, except that the abstract class can contain some concrete implementation. For example, the animal class should be an abstract class, and its subclasses include cats, dogs, pandas and so on. They are all animals and have some common characteristics. After you define a class as an abstract class, you can no longer new instances and can only be inherited by its subclasses.
Abstract defines the abstract class, the class uses abstract to define an abstract method, and the subclass must implement the abstract method.
Abstract class Animal {eat (food:string) {console.log (`eat ${food} `on the ground);} abstract run (behavior:string): void} / / cat class Dog extends Animal {run (behavior:string): void {console.log (behavior);}} const D1 = new Dog () D1.eat ('bone') d1.run ('four-legged crawl') / / rabbit class rabbit extends Animal {run (behavior:string): void {console.log (behavior);}} const R1 = new rabbit (); d1.eat ('radish') d1.run ('bouncing') 13. Generics
Generics do not specify a specific type when defining a function, interface, or class and do not specify a specific type until it is used. Reuse code to a great extent.
For example, there is an identity function that returns any value passed in to it, and the type passed in should be the same as the type returned. If you pass in a number without generics,
This function might look like this:
Function identity (arg:number): number {return arg} if you pass in a string, the function might look like this: function identity (arg:string): string {return arg} is too troublesome, so you can use generics, which are generally represented by uppercase T, which can be applied to multiple types, and the incoming type is the same as the return type. Function identity (arg:T): t {return arg} above is all the content of the article "what are the basic grammars of Typescript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.