Typescript record (I)

Karsuo 2021-09-15 06:31:16
typescript record


1- return type

function add(first:number, second:number): number {
return first + second
}
const total = add(1,2)
 Copy code 

2-void type , The return value is null , I hope not return value

function say(): void {
console.log("122")
}
 Copy code 

3-never type , It can never be carried out to the end

function error(): never {
throw new Error()
console.log("1111")
}
 Copy code 

4- Deconstruction syntax definition type

function add({first, second}: {first:number, second:number}): number {
return first + second
}
add({first:1,second:2})
 Copy code 

5- The base type boolean,number,string,void,undfined,symbol,null

let count: number;
count = 100
 Copy code 

6- object type ,{},Class, function, []

const func = (str:string): number => {
return parseInt(str, 10)
}
const func:(str: string) => number = (str) => {
return parseInt(str, 10)
}
interface Person {
name: string
}
const q = "{"name": "jack"}";
const b: Person = JSON.parse(q);
 Copy code 

7- Or type |

let temp: number | string = 124;
temp = "1212"
 Copy code 

8- Array

const arr: (number | string)[] = [1,'2',3]
const strArr: string[] = ['d','f','g']
const undefinedArr: undefined[] = [undefined]
const objectArr: {name: string, age: number}[] = [{
name:'jack',
age: 26
}]
 Copy code 

9- Type the alias type

type User = {name: string, age: number}
const objectArr: User[] = [{
name:'jack',
age: 26
}]
 Copy code 

10- Tuples

const info: [string, string, number] = ['jack', 'ben', 100]
 Copy code 

11-interface

interface Person {
readonly tag: string // readonly Indicates that the property is read-only , You can't overwrite it
name: string,
age?: number // ? Indicates that the attribute is optional
[propName: string]: any // I can also have extra Other attributes , As long as the specifications are met
say(): string
}
const setName = (person: Person, name): void => {
person.name = name;
}
setName({name: "jack"}, "duke")
const a = {
name: "jack",
say(){
return "kao "
}
}
// [propName: string]: any
setName({ name: "jack",sex: "niu"}, "duke")
It's better to pass parameters with variables than with literal parameters , Direct assignment with self surface quantity is passed to the participant for strong verification , If you use variables to pass values slowly, it won't be so strict
 Copy code 

12- One class Class wants to apply a interface Interface

class User implements Person {
name: "dragon",
say() {
return "gan"
}
}
 Copy code 

13- Interfaces can inherit from each other

 In addition to Person Attribute outside , There has to be more Teacher In the properties of the , If you are :Teacher
interface Teacher extends Person {
teach(): string
}
 Copy code 

14- Define function interface types

interface SayHi {
(word: string): string
}
const say: SayHi = (word: string) => {
return word
}
 Copy code 

15- Class definition and inheritance super usage

super The method used to call the parent class
class Person {
name: 'jack',
getName() {
return this.name
}
}
class Teacher extends Person {
getTeach() {
return "teach"
}
getName() {
return super.getName() + 'duke!!!'
}
}
 Copy code 

16- private, protected, public Access type

 The default is public type , Allow to be called inside and outside the class
private type , Allow to be used within a class
protected type , It is allowed to use... Within a class and in inherited subclasses
class Person {
private name: string,
// protected name: string,
public sayHi() {
this.name;
console.log("name~~~")
}
}
class Teacher extends Person {
public sayBye() {
this.name
}
}
const person = new Person();
person.name = "ben";
console.log(person.name)
person.sayHi()
 Copy code 

17- constructor Instantiation

 When instantiating constructor() This method will be executed automatically in an instant , It can receive the transmitted parameters
// The traditional way of writing
class Person {
public name: string,
constructor(name: string){
this.name = name
}
}
// Simplify writing
class Person {
constructor(public name: string){ }
}
const person = new Person('jack')
 Copy code 

18- . If the parent class has constructor Constructors ( And it's worth it ), When subclasses also declare constructors , You must manually call the constructor of the parent class in the subclass

  • super Refers to the parent class
  • super() It refers to calling the constructor of the parent class
class Person {
constructor(public name: string){ }
}
class Teacher extends Person {
constructor(public age: number) {
super('jack')
}
}
const teacher = new Teacher(1000);
 Copy code 

19- . If the parent class does not write constructor Constructors ( No value ), You must manually call the constructor of the parent class in the subclass super() empty

class Person { }
class Teacher extends Person {
constructor(public age: number) {
super()
}
}
const teacher = new Teacher(1000);
 Copy code 

20- Static attribute (getter obtain , setter assignment )

  • private Represents a private property
  • _ Add... Before attribute _ It also means private property
class Person {
constructor(private _name: string){ }
get name() {
return this._name + " ben"
}
set name(name: string) {
const realName = name.split(" ")[0]
this._name = realName
}
}
const person = new Person("duke")
person.set = 'duke ben'
 Copy code 

21- The singleton pattern ( That is, only one instance can be generated forever )

  • static Just mount this method directly on the class , Instead of an instance of a class
class Demo {
private static instance: Demo;
private constructor(public name: string) {} // If you declare it private , You can't use new External call
static getInstance() {
if(!this.instance){
this.instance = new Demo("jack");
}
return this.instance;
}
}
// Logically speaking demo1 and demo2 Are all the same instances
const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
 Copy code 

22- readonly You can only read but not change

class Person {
public readonly name: string
constructor(name: string){
this.name = name
}
}
const person = new Person("jack")
person.name = "dragon" // Report errors , Because it's set up readonly
 Copy code 

23- abstract class ( Pull out the common things , You can set abstract methods , Or actual methods and properties )

  • If an abstract class has abstract methods ,extends Inheritance time , To achieve it, or there will be a red error
abstract class Geom {
width: number;
getType() {
return "Geom"
}
abstract getArea(): number
}
class Circle extends Geom {
getArea() {
return 100
}
}
 Copy code 

Conclusion

front end react QQ Group :788023830 ---- React/Redux - Old underground hero

Front end communication QQ Group :249620372 ---- FRONT-END-JS front end

( Our purpose is , To work overtime , For baldness ……, Look up to the big guy ), I hope my friends can study together

版权声明
本文为[Karsuo]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909122358684i.html

  1. Flutter: résoudre le futur blocage en utilisant Isolate
  2. Résumé des opérations courantes pour les données de structure de l'arbre frontal
  3. Ant Design Transfer Twin Tree Shuttle box "make Wheels"
  4. De la carte de pensée à la base et à l'approfondissement, prenez note de l'expérience d'entrevue d'un octet sautant le poste de recherche et développement Java.
  5. Apprenez les composants d'implémentation de vue et Publiez - les à NPM
  6. [Questions d'entrevue à haute fréquence] À vous de choisir
  7. Une faible connaissance de beginpath () provoque une superposition de style lors de la peinture d'un dessin en toile
  8. React Hooks, laisse - moi t'emmener étudier.
  9. Comment la copie profonde résout - elle les références circulaires?
  10. JavaScript Advanced Programming (3rd Edition) Reading note 6
  11. Analyse de l'URL
  12. Discussion préliminaire sur xss
  13. Solution: développement de la page Web Wechat, obtenir la fosse Piétinée par le flux d'entrée de la caméra via navigator.mediadevice.getusermedia ()
  14. Des milliers de questions d'entrevue sélectionnées n'ont pas encore ét é effacées.
  15. Les questions d'entrevue de niveau intermédiaire et avancé d'Android au fil des ans sont entièrement incluses, et l'algorithme est distribué microservice
  16. J'ai résumé toutes les questions d'entrevue.
  17. Compréhension de la réactivité des données de vue
  18. Note de service CSS (vi): Flex, page mobile et mise en page réactive
  19. Non-ASCII character ‘\xe5‘ in file kf1.py on line 4, but no encoding declared; see http://python.or
  20. 手把手教你搭建微信小程序服务器(HTTPS)
  21. JavaScript Review sketch - 1
  22. Analyse du bootstrap webpack
  23. sqli-labs-less-18 http头user agent+报错注入
  24. Génération de code nest pour l'outil CLI de nestjs
  25. JS | This
  26. Augmentation des variables
  27. The sinking gs8 raises its flag again. GAC motor's sales are falling endlessly. Is it the car or the people?
  28. Ren Hao's lunch at work today is president Hao wearing a sleeveless coat! Clean and handsome!
  29. Summary of basic knowledge points of JavaScript language (mind map)
  30. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  31. Sqli Labs - less - 18 http header user agent + Error Reporting Injection
  32. Vous apprendrez à construire un serveur d'applet Wechat (https) à la main
  33. Non - ASCII character 'xe5' in file kf1.py on Line 4, but no Encoding declared;Voirhttp://python.or
  34. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  35. En tant que programmeur, quelle est la plus grande tristesse que vous ressentez? L'entrevue d'emploi Java de 2021 dans une grande usine vous demandera:
  36. En tant que programmeur, je n'oublie pas le dernier résumé de mon expérience d'entrevue de stage en Java.
  37. Experts suggested that performers work with certificates, which triggered a collective heated debate. It is meaningless to be accused of repeating the mistakes
  38. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  39. The appearance value of 200000 "Odyssey" is less than 100000, and has become the "sales champion" of household MPV
  40. Les programmeurs Java qui sont entrés dans l'entreprise pendant trois mois ont dû faire face à une correction d'échelle, et les octets ont sauté dans le traitement des questions d'entrevue de JD 360 Netease.
  41. 350 questions d'entrevue Android partage, technologie d'architecture de cache
  42. The space is not vulgar, the configuration is rich, the leather is durable, less worry, and the high configuration is less than 100000!
  43. Vous permet de passer rapidement à travers l'entrevue de saut d'octets et d'aller de l'avant
  44. Résumé des questions d'entrevue technique d'Alibaba Baidu et d'autres grandes usines à la fin de l'année, et analyse de la dernière vraie question d'entrevue Android en 2021
  45. Avec cet ensemble de questions d'entrevue Java, l'ensemble de questions de base d'entrevue de bat,
  46. Avec cet ensemble de questions d'entrevue Java, les notes avancées Java de niveau divin sont systématisées,
  47. Opérateurs arithmétiques et opérateurs de comparaison pour JavaScript, Introduction classique au développement web
  48. Explorer le cadre open source Android - 1. Okhttp Source Analysis
  49. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  50. Partager l'expérience de l'examen et du développement de l'arrière - plan, en s'appuyant sur les questions d'entrevue et les réponses,
  51. Site Web pour partager vos expériences d'entrevue, Tencent Bull vous apprend à écrire votre propre cadre Java!
  52. Notes d'étape Android structurées, sélection de vrais problèmes d'entrevue Android
  53. Dictionnaire distribué: communication de cache limitée par le courant, sujets d'entrevue pour certaines questions courantes dans le développement Java,
  54. Tianci girlfriend Tangyuan attended the event for the second time. Her appearance was comparable to that of a star. The audience shouted that Tianci was blessed!
  55. Introduction au JavaScript chapitre 15 (objets, clairvoyance)
  56. La dernière revue scientifique de l'académicien Luo Liqun: architecture de la boucle neuronale pour stimuler la nouvelle Ia
  57. Basic knowledge of components in Vue "I"
  58. J'a i appris quelques petites choses sur l'entrevue et j'ai acheté un tutoriel en 19998.
  59. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  60. Want to know the implementation and application of single instance mode in the front end?