Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interfaces and generics in TypeScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about what interfaces and generics are in TypeScript. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Interface

Use the interface keyword to define the data type

Object Typ

When there is a longer data type constraint, we can annotate the type with the type keyword, or we can define it through the interface

Type UserType = {name: string; age?: number}; const user: UserType = {name: "kiki", age: 18,}; interface IUserType {name: string; age?: number} const person: IUserType = {name: 'alice', age: 20} Index Type

Both interface and type definition objects can be defined when only the type of key is known and the specific key value is not known.

Interface ILanguage {[index: number]: string;} const language: ILanguage = {0: "html", 1: "css", 2: "js",}; type Score = {[name: string]: number;} const score: Score = {Chinese: 120, math: 95, Englist: 88,}; function type

The syntax for interface and type is slightly different when defining a function

Interface ISelfType {(arg: string): string;} type LogType = (arg: string) = > string;function print (arg: string, fn: ISelfType, logFn: LogType) {fn (arg); logFn (arg);} function self (arg: string) {return arg;} console.log (print ("hello", self, self)); inheritance

The interface can implement multiple inheritance, and the inherited interface has all the type annotations of the parent class.

Interface ISwim {swimming: () = > void;} interface IEat {eating: () = > void;} interface IBird extends ISwim, IEat {} const bird: IBird = {swimming () {}, eating () {},}; Cross type

The cross-type is actually the operation of and. After the interface is operated with the & symbol, it is essentially necessary to satisfy all the type comments of the interface with the operation.

Interface ISwim {swimming: () = > void;} interface IEat {eating: () = > void;} type Fish = ISwim | IEat;type Bird = ISwim & IEat;const fish: Fish = {swimming () {},}; const bird: Bird = {swimming () {}, eating () {},}; export {} API implementation

Interfaces can be implemented through classes using the implements keyword. Classes can inherit only one parent class, but can implement multiple interfaces

Interface ISwim {swimming: () = > void} interface IEat {eating: () = > void} class Animal {} class Fish extends Animal implements ISwim, IEat {swimming () {} eating () {} class Person implements ISwim {swimming () {}} function swimAction (iswim: ISwim) {iswim.swimming ()} swimAction (new Fish ()) swimAction (new Person ())

If there is no class that implements the interface, naturally there are no methods in the interface

The difference between interface and type

In many cases, interface and type are the same, but one obvious difference is that interface can be defined repeatedly, type annotations will accumulate, and type duplicate definitions will report an error.

Literal quantity assignment

When you directly assign a literal value type to a variable, the literal quantity will be type inferred, and the extra attributes will report an error.

However, if the reference to the object is assigned, the freshness erase operation will be performed, and the redundant attributes will be erased during type checking. If the type is still satisfied, the value can be assigned.

Enumerated type

Enumerated types are defined by the enum keyword, which is similar to the function of federated types, but the code of enumerated types is more readable.

Enum Direction {LEFT, RIGHT, TOP, BOTTOM,} function turnDirection (direction: Direction) {switch (direction) {case Direction.LEFT: break; case Direction.RIGHT: break; case Direction.TOP: break; case Direction.BOTTOM: break; default: const foo: never = direction; break;}} turnDirection (Direction.LEFT); generic function

When the type of the input parameter is uncertain, you can annotate the type as generic, and then specify the specific type when you use it, and use it to define the generic type.

Function self (element: t) {return element;} self ("alice"); self (2); self (null)

If no type is defined, ts will do type derivation, which may not be the type we want, for example, the following string derives not a "string" string type, but a "hello" literal type.

When there are multiple parameters, you can define multiple parameters in the generic type.

Function foo (a: t, b: e, c: O) {} foo (1, 'alice', false) foo ([' alice'], undefined, null) generic interface

Use generics in an interface to write type comments after the interface name

Interface Person {name: t; age: e;} const person: Person = {name: "alice", age: 20,}

It is impossible to derive a type by using generics in an interface, and you must specify a specific type when using it.

Unless the default value is set for generics when the interface is defined

Interface Book {category: t; price: e;} const book: Book = {category: "nature", price: 88.6,}; const dictionary: Book = {category: 1, price: '88'} generic class

The method defined in the class simply replaces the specific data type with generics, and the type can be inferred in the class

Class Point {x: t; y: t; z: t; constructor (x: t, y: t, z: t) {this.x = x; this.y = y; this.z = z;}} new Point ("1.55,2.34,3.67"); new Point (1.55,2.34,3.67); type constraint

Generics can be constrained by inheritance.

Only the parameter passed in satisfies the condition of the generic type, that is, the length attribute

Interface ILength {length: number;} function getLength (element: t) {return element.length;} getLength ("alice"); getLength (["alice", "kiki", "lucy"]); getLength ({length: 5})

Interfaces, enumerations, and generics are not available in JavaScript, but they are all very important type annotations in TypeScirpt.

Thank you for reading! This is the end of the article on "what are interfaces and generics in TypeScript". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report