In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the skills in TypeScript". In daily operation, I believe that many people have doubts about the skills in TypeScript. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what are the skills in TypeScript?" Next, please follow the editor to study!
1. Annotation
The TS type can be marked and prompted by comments in the form of / *, and the editor will have a better prompt:
/ * This is a cool guy. * / interface Person {/ * * This is name. * / name: string,} const p: Person = {name: 'cool'}
This is a good way to add comments or friendly prompts to a property.
two。 Interface inheritance
Like classes, interfaces can inherit from each other.
This allows us to copy members from one interface to another, giving us more flexibility to split the interface into reusable modules.
Interface Shape {color: string;} interface Square extends Shape {sideLength: number;} let square = {}; square.color = "blue"; square.sideLength = 10
An interface can inherit multiple interfaces and create a composite interface of multiple interfaces.
Interface Shape {color: string;} interface PenStroke {penWidth: number;} interface Square extends Shape, PenStroke {sideLength: number;} let square = {}; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0; interface & type
There are two ways to define types in TypeScript: interfaces (interface) and type aliases (type alias).
For example, in the following examples of Interface and Type alias, except for syntax, the meaning is the same:
Interfaceinterface Point {x: number; y: number;} interface SetPoint {(x: number, y: number): void;} Type aliastype Point = {x: number; y: number;}; type SetPoint = (x: number, y: number) = > void
And both can be extended, but the syntax is different. In addition, note that interfaces and type aliases are not mutually exclusive. Interfaces can extend type aliases and vice versa.
Interface extends interfaceinterface PartialPointX {x: number;} interface Point extends PartialPointX {y: number;} Type alias extends type aliastype PartialPointX = {x: number;}; type Point = PartialPointX & {y: number;}; Interface extends type aliastype PartialPointX = {x: number;}; interface Point extends PartialPointX {y: number;} Type alias extends interfaceinterface PartialPointX {x: number;} type Point = PartialPointX & {y: number;}
The difference can be found in the following picture or at TypeScript: Interfaces vs Types.
So it's not easy to use interface & type skillfully.
If you don't know what to use, remember: if you can do it in interface, use interface, and if you can't, use type.
4. Typeof
The typeof operator can be used to get the type of a variable or object.
We usually define the type before using:
Interface Opt {timeout: number} const defaultOption: Opt = {timeout: 500}
Sometimes it can be reversed:
Const defaultOption = {timeout: 500} type Opt = typeof defaultOption
When an interface always has a literal initial value, you can consider this way of writing to reduce duplication of code, reducing at least two lines of code, right? ~
5. Keyof
TypeScript allows us to traverse a certain type of attribute and extract the name of its attribute through the keyof operator.
The keyof operator, introduced in TypeScript 2.1, can be used to get all keys of a type whose return type is a union type.
Keyof is slightly similar to Object.keys, except that keyof takes the key of interface.
Const persion = {age: 3, text: 'hello world'} / / type keys = "age" | "text" type keys = keyof Point
When writing a method to get the value of a property in an object, the average person might write this
Function get1 (o: object, name: string) {return o [name];} const age1 = get1 (persion, 'age'); const text1 = get1 (persion,' text')
But it will prompt to report an error.
Because there is no pre-declared key in object.
Of course, if you change o: object to o: any, there will be no error, but the value you get will have no type and will become any.
At this point, you can use keyof to enhance the type function of the get function. Interested students can take a look at the type tag and implementation of _ .get
Function get (o: t, name: K): t [K] {return o [name]}
6. Find type interface Person {addr: {city: string, street: string, num: number,}}
When you need to use a type of addr, in addition to bringing up the type
Interface Address {city: string, street: string, num: number,} interface Person {addr: Address,}
It's okay
Person ["addr"] / / This is Address.
For example:
Const addr: Person ["addr"] = {city: 'string', street:' string', num: 2}
In some cases, the latter makes the code cleaner and easier to read.
7. Find types + generics + keyof
Generics is a property that specifies a type without specifying a specific type in advance when defining a function, interface, or class.
Interface API {'/ user': {name: string},'/ menu': {foods: string []} const get = (url: URL): Promise = > {return fetch (url) .then (res = > res.json ());} get (''); get ('/ menu') .then (user = > user.foods)
8. Type assertion
Ref is often used in Vue components to get the properties or methods of sub-components, but it is often impossible to infer what properties and methods there are, and errors will be reported.
Subcomponents:
Import {Options, Vue} from "vue-class-component"; @ Options ({props: {msg: String,},}) export default class HelloWorld extends Vue {msgems: string;}
Parent component:
Import {Options, Vue} from "vue-class-component"; import HelloWorld from "@ / components/HelloWorld.vue"; / / @ is an alias to / src @ Options ({components: {HelloWorld,},}) export default class Home extends Vue {print () {const helloRef = this.$refs.helloRef; console.log ("helloRef.msg:", helloRef.msg);} mounted () {this.print ();}}
Because this.$refs.helloRef is an unknown type, an error message will be reported:
Just make a type assertion:
Print () {/ / const helloRef = this.$refs.helloRef; const helloRef = this.$refs.helloRef as any; console.log ("helloRef.msg:", helloRef.msg); / / helloRef.msg: Welcome to Your Vue.js + TypeScript App}
But it is not good when the type assertion is any, if you know the specific type, it is good to write the specific type, otherwise it seems meaningless to introduce TypeScript.
9. Explicit generics
$('button') is a DOM element selector, but the type of return value can only be determined at run time. In addition to returning any, you can also
Function $(id: string): t {return (document.getElementById (id)) as T;} / / uncertain input type / / const input = $('input'); / / Tell me what element it is. Const input = $('input'); console.log (' input.value:', input.value)
Function generics do not have to derive the type automatically; sometimes it is good to specify the type explicitly.
10. DeepReadonly
Attributes marked by readonly can only be assigned at declaration time or in the constructor of the class.
After that, it cannot be changed (that is, the read-only property), otherwise a TS2540 error will be thrown.
It is similar to const in ES6, but readonly can only be used on attributes in a class (TS can also be an interface), which is equivalent to a syntactic sugar with an attribute of getter without setter.
The following implements a type of deeply declared readonly:
Type DeepReadonly = {
Readonly [P in keyof T]: DeepReadonly
}
Const a = {foo: {bar: 22}}
Const b = an as DeepReadonly
B.foo.bar = 33 / / Cannot assign to 'bar' because it is a read-only property.ts (2540)
At this point, the study of "what are the skills in TypeScript" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.