Learn about TypeScript data types in one article

Learn about TypeScript data types in one article

Basic Types

More types are supported in ts

let age: number = 10 // Number
let firstName: string = '凉宸' // String
let lastName: string = '凉宸' // String
let isMary: boolean = true // boolean
let unde: undefined = undefined // undefined
let nu: null = null // null

undefined and null can be assigned as values ​​to other types because they can be considered subtypes of other types.

When assigning values, you must do so according to the defined data type, otherwise there will be the following error message

  • When declaring a variable, the type does not match the value
  • When reassigning a variable, the type does not match the value

insert image description here

insert image description here

insert image description here

insert image description here

any type

Sometimes we cannot determine the type of a variable, we can specify it as any

When we assign a value to the any type, we can assign any value to it without reporting an error.

let isAny:any='any type any'
isAny=520
isAny=true
isAny=null

However, in order to avoid type ambiguity, we should try to use any as little as possible.

Characteristics of any type

  • Allows assignment of any type
  • Can access any properties and methods
let userName: any = '凉宸';
// You can access any property console.log(userName.name);
console.log(userName.name.firstName);
// You can call any method userName.setName('David');
userName.setName('David').sayHello();
userName.name.setFirstName('David');

Arrays

We can specify the type of elements in the array

let ages: number[] = [5, 20, 13, 14]
let names: string[] = ['Liang Chen', 'Luffy', 'Ming Shiyin', 'Li Yangyong']

insert image description here

insert image description here

Array-like:

Class arrays do not have the methods that arrays have. tsc can automatically identify the two.

let arguments = [555,555,55]

function lei(){
  let arr:number=arguments
}

insert image description here

Tuple

Basically similar to an array, but the type can be multiple

let arr:[number,string,boolean]=[520,'凉宸',true] 

insert image description here

When assigning values, we must fill in the order of types.

insert image description here

insert image description here

More elements are better than less

let arr:[number,string,boolean]=[520,'凉宸',true]
arr.push('b') // OK arr.push(4) // OK arr.push(true) // OK console.log(arr)
let arr:[number,string]=[520,'凉宸']
arr.push('b') // OK arr.push(4) // OK arr.push(true) // No console.log(arr)

insert image description here

Interface

  • An interface can be understood as a program, which is relatively abstract and does not specify specific behaviors. That is to say, in an interface, we only define properties, methods, and types of properties, and abstract methods. We will not assign values ​​to properties or define method implementations.
  • For classes, properties generally need to be assigned values, and methods must also be implemented.
  • Interface declarations are like classes, and members are more like literal objects than classes.

effect:

  • Describe the shape of the object
  • Duck Typing
interface Point
  userName:string|number
  password:number
} // At this time, executing tsc will not parse the corresponding js code, because this type is unique to ts and only indicates constraints
interface Point
  userName:string|number
  password:number
}

let value:Point={
  userName:'[email protected]',
  password:123456
}

let val:Point={
  userName:55555,
  password:123456
} // At this time, both are met, and tsc is executed


// Only the following code appears, without any constraints js
var value = {
    userName: '[email protected]',
    password: 123456
};
var val = {
    userName: 55555,
    password: 123456
};

Optional attributes ?

When creating an IPerson interface type variable, the attributes declared in the interface must also be present when assigning a value to the variable, otherwise an error will be reported.

But we can set a property as optional, and when creating a variable, we can choose to assign a value

interface Point
  userName:string|number
  password:number,
  email?:string
}

let value:Point={
  userName:'[email protected]',
  password:123456
}

let val:Point={
  userName:55555,
  password:123456
}

insert image description here

Read-only attribute readonly :

interface Point
  userName:string|number
  password:number,
  email?:string,
  readonly address:string
}

let value:Point={
  userName:'[email protected]',
  password:123456,
  address:'Baoding'
}

let val:Point={
  userName:55555,
  password:123456,
  address:'Beijing'
}
value.password=65975222
value.address = 'kkk'

insert image description here

function

Functions in ts can define return value types

const value=():number=>{
  return 1
}

const val=():string=>{
  return 1
}

insert image description here

insert image description here

Type self-deduction

When we define a variable without assigning a type, it will be inferred according to the value.

let value=5555

value='string'

insert image description here

Union type (choose one or more)

let value:string|number
value = '凉辰'
value=520
value=true

insert image description here

Type Assertion:

function get(data:string|number):number{
  const str = data as string
  if(str.length){
    return str.length
  }else {
    const num = data as number
    return num.toString().length
  }
}

console.log(get('凉宸'));
console.log(get(520));

insert image description here

  • Assertions using as
  • Assertions are not type conversions. They just tell the compiler the type of the variable, and you will get a hint when you use the variable later.
  • If you don't add an assertion, an error will be reported when using a certain type of method

type guard:

type guard is not a type, but a mechanism that can confirm a specific type.

function get(data:string|number):number{
  if(typeof data==='string'){
    return data.length
  }else {
    return data.toString().length
  }
}

console.log(get('凉宸'));
console.log(get(520));

insert image description here

class

class: class, ES6 syntax, is the object-oriented promotion of js, class is just syntactic sugar, the underlying implementation is still based on functions and prototypes

  • Class: defines the abstract characteristics of everything, like a blueprint, a drawing
  • Object: An instance of a class
  • Three major features: encapsulation, inheritance, and polymorphism

Three modifiers can control the access level of members in a class:

  • Public: The modified property or method is public and can be accessed from anywhere. The default behavior
  • Protected: The modified property or method is protected and can only be accessed by the class itself and its subclasses.
  • Private: The modified property or method is private and can only be accessed within the class.
class Person {
  public name:string
  protected age:number
  private address:string
  constructor(name:string,age:number,address:string){
    this.name=name
    this.age=age
    this.address=address
  }
  speak(){
    console.log(`Person:${this.name}---${this.age}---${this.address}`)
  }
}
const Children = new Person('凉宸',20,'宝定')
Children.speak()
//Can output normally 

insert image description here

class Person {
  public name:string
  protected age:number
  private address:string
  constructor(name:string,age:number,address:string){
    this.name=name
    this.age=age
    this.address=address
  }
  speak(){
    console.log(`Person:${this.name}---${this.age}---${this.address}`)
  }
}

class child extends Person {
  say(){
    console.log(`child:${this.name}---${this.age}`)
  }
}
// const Children = new Person('凉宸',20,'宝定')
// Children.speak()
const children = new child('凉宸',20,'宝定')
children.say()

insert image description here

It also reports an error when running

insert image description here

class Person {
  public name:string
  protected age:number
  private address:string
  constructor(name:string,age:number,address:string){
    this.name=name
    this.age=age
    this.address=address
  }
  speak(){
    console.log(`Person:${this.name}---${this.age}---${this.address}`)
  }
}

class child extends Person {
  say(){
    console.log(`child:${this.name}---${this.age}`)
  }
}
// const Children = new Person('凉宸',20,'宝定')
// Children.speak()
const children = new child('凉宸',20,'宝定')
children.say()

insert image description here

class Person {
  public name:string
  protected age:number
  private address:string
  constructor(name:string,age:number,address:string){
    this.name=name
    this.age=age
    this.address=address
  }
  speak(){
    console.log(`Person:${this.name}---${this.age}---${this.address}`)
  }
}

class child extends Person {
  say(){
    console.log(`child:${this.name}---${this.age}`)
  }
}
const Children = new Person('凉宸',20,'宝定')
Children.speak()
console.log(Children.address);
console.log(Children.age);

// const children = new child('凉宸', 20, '宝定')
// children.say()

insert image description here

insert image description here

insert image description here

enumerate

Enumeration type is used in scenarios where the value is limited to a certain range.

enum Week {
  SUNDAY = 'Sunday',
  MONDAY = 'Monday',
  TUESDAY = 'Tuesday',
  WEDNESDAY = 'Wednesday',
  THURSDAY = 'Thursday',
  FRIDAY = 'Friday',
  SATURDAY = 'Saturday'
}
function getProgramme(date: Week): string {
  if (date === Week.SUNDAY) {
  return 'Sunday leisure and entertainment'
  } else if (date === Week.MONDAY) {
  return 'Blog post on Monday'
  } else if (date === Week.TUESDAY) {
  return 'Tuesday sprint'
  }
  else if (date === Week.WEDNESDAY) {
  return 'Continue to fight on Wednesday'
  }
  else if (date === Week.THURSDAY) {
  return 'New article on Thursday'
  }
  else if (date === Week.FRIDAY) {
  return 'Ready to rest on Friday'
  }
  else {
  return 'Sleep on Saturday'
  }
  }
  console.log(getProgramme(Week.THURSDAY));

insert image description here

This is the end of this article about understanding TypeScript data types. For more information about TypeScript data types, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code using Typescript in Vue
  • Do you understand functions and classes in TypeScript?
  • Do you understand interfaces and generics in TypeScript?
  • TypeScript Enumeration Type
  • Introduction to TypeScript basic types
  • Detailed explanation of how to use TypeScript type annotations

<<:  Linux bridge method steps to bridge two VirtualBox virtual networks

>>:  How to quickly use mysqlreplicate to build MySQL master-slave

Recommend

Implementation of Docker CPU Limit

1. --cpu=<value> 1) Specify how much availa...

WeChat applet implements simple chat room

This article shares the specific code of the WeCh...

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction Vue.js allows you to define...

Complete steps to configure a static IP address for a Linux virtual machine

Preface In many cases, we will use virtual machin...

Basic tutorial on controlling Turtlebot3 mobile robot with ROS

Chinese Tutorial https://www.ncnynl.com/category/...

Full analysis of MySQL INT type

Preface: Integer is one of the most commonly used...

Implement 24+ array methods in JavaScript by hand

Table of contents 1. Traversal Class 1. forEach 2...

Docker time zone issue and data migration issue

Latest solution: -v /usr/share/zoneinfo/Asia/Shan...

Analysis of GTK treeview principle and usage

The GtkTreeView component is an advanced componen...

Installation tutorial of MySQL 5.1 and 5.7 under Linux

The operating system for the following content is...

This article takes you to explore NULL in MySQL

Table of contents Preface NULL in MySQL 2 NULL oc...

MYSQL Operator Summary

Table of contents 1. Arithmetic operators 2. Comp...