当前位置:网站首页>TypeScript(1-2-2)

TypeScript(1-2-2)

2020-11-08 16:10:35 Charon

typescript yes jiavascript Here are some simple usages , Please check the official website for more details .
typescript Official website

typescript It's progressive , If you are not familiar with some grammar , It doesn't matter , We can follow exactly javascript The syntax of .

Raw data type


const a: string = 'foobar'

const b: number = 100 // NaN Infinity

const c: boolean = true // false

//  In the non strict mode (strictNullChecks) Next ,
// string, number, boolean  Can be empty 
// const d: string = null
// const d: number = null
// const d: boolean = null

const e: void = undefined

const f: null = null

const g: undefined = undefined

// Symbol  yes  ES2015  Members defined in the standard ,
//  The premise of using it is to ensure that there is a corresponding  ES2015  Standard library references 
//  That is to say  tsconfig.json  Medium  lib  Options must contain  ES2015
const h: symbol = Symbol()

// Promise

// const error: string = 100

Scope problem : Members in the default file will be global members , If there is the same member in multiple files, there will be conflicts .

terms of settlement 1: IIFE Provide independent scopes
(function () {
const a = 123
})()
terms of settlement 2: Use... In the current file export, That is to turn the current file into a module
Modules have separate scopes
const a = 123

export {}

The following records are exported by default module , There is a module scope .

Object type

object A type is a type other than the original type
const foo: object = function () {} // [] // {}

If you need to explicitly restrict object types , This type of object literal syntax should be used , Or is it 「 Interface 」

const obj: { foo: number, bar: string } = { foo: 123, bar: 'string' }

An array type

Two representations of array types

const arr1: Array<number> = [1, 2, 3]

const arr2: number[] = [1, 2, 3]

Case study :

//  If it is  JS, We need to judge whether each member is a number 
//  Use  TS, The type is guaranteed , No need to add type judgment 
function sum (...args: number[]) {
  return args.reduce((prev, current) => prev + current, 0)
}

sum(1, 2, 3) // => 6

Tuples

We know that the data types of elements in an array are generally the same (any[] Arrays of types can be different ), If the stored element data types are different , You need to use tuples .

Tuples allow different types of elements to be stored , Tuples can be passed to functions as arguments .

const tuple: [number, string] = [18, 'zce']
const [age, name] = tuple

const entries: [string, number][] = Object.entries({
  foo: 123,
  bar: 456
})

const [key, value] = entries[0]

enumeration (Enum)

Standard enumeration of numbers

enum PostStatus {
  Draft = 0,
  Unpublished = 1,
  Published = 2
}

 Enumeration of numbers , Enumeration values are automatically incremented based on the previous value 
enum PostStatus {
  Draft = 6,
  Unpublished, // => 7
  Published // => 8
}

 String Enum 
enum PostStatus {
  Draft = 'aaa',
  Unpublished = 'bbb',
  Published = 'ccc'
}
//  Constant enumeration , Does not intrude into the compilation results 
const enum PostStatus {
  Draft,
  Unpublished,
  Published
}
const post = {
  title: 'Hello TypeScript',
  content: 'TypeScript is a typed superset of JavaScript.',
  status: PostStatus.Draft // 3 // 1 // 0
}

Function type

function func1 (a: number, b: number = 10, ...rest: number[]): string {
  return 'func1'
}

const func2: (a: number, b: number) => string = function (a: number, b: number): string {
  return 'func2'
}

Any type ( Weak type )

function stringify (value: any) {
  return JSON.stringify(value)
}
let foo: any = 'string'

any Type is not safe

Interface

Any value object in the code

interface Post {
  title: string
  content: string
}

function printPost (post: Post) {
  console.log(post.title)
  console.log(post.content)
}

printPost({
  title: 'Hello TypeScript',
  content: 'A javascript superset'
})

interface Post {
  title: string
  content: string
  subtitle?: string// Optional 
  readonly summary: string// read-only 
}

const hello: Post = {
  title: 'Hello TypeScript',
  content: 'A javascript superset',
  summary: 'A javascript'
}

interface Cache {
  [prop: string]: string
}
// Define the object property name as a string , Values are also strings 

const cache: Cache = {}

cache.foo = 'value1'
cache.bar = 'value2'

class

class Person {
  name: string // = 'init name'
  age: number
  
  constructor (name: string, age: number) {
    this.name = name
    this.age = age
  }

  sayHi (msg: string): void {
    console.log(`I am ${this.name}, ${msg}`)
  }
}


class Person {
  public name: string // = 'init name'
  private age: number // private   When members are marked with private when , It can't be accessed outside the class that declares it 
  protected gender: boolean //protected and private similar , however ,protected Members can be accessed in derived classes 
  
  constructor (name: string, age: number) {
    this.name = name
    this.age = age
    this.gender = true
  }

  sayHi (msg: string): void {
    console.log(`I am ${this.name}, ${msg}`)
    console.log(this.age)
  }
}

class Student extends Person {
 //  Read only members 
  protected readonly gender: boolean
  private constructor (name: string, age: number) {
    super(name, age)
    this.gender = true;// Initial assignment is required 
    console.log(this.gender)
  }

  static create (name: string, age: number) {
    return new Student(name, age)
  }
}

const tom = new Person('tom', 18)
console.log(tom.name)
// console.log(tom.age)
// console.log(tom.gender)

const jack = Student.create('jack', 18)

Classes and interfaces


interface Eat {
  eat (food: string): void
}

interface Run {
  run (distance: number): void
}

class Person implements Eat, Run {
  eat (food: string): void {
    console.log(` An elegant meal : ${food}`)
  }

  run (distance: number) {
    console.log(` Walk upright : ${distance}`)
  }
}

class Animal implements Eat, Run {
  eat (food: string): void {
    console.log(` Snoring and eating : ${food}`)
  }

  run (distance: number) {
    console.log(` crawl : ${distance}`)
  }
}

Thread drawing class Can only be inherited

abstract class Animal {
  eat (food: string): void {
    console.log(` Snoring and eating : ${food}`)
  }

  abstract run (distance: number): void
}

class Dog extends Animal {
  run(distance: number): void {
    console.log(' Crawling on all fours ', distance)
  }

}

const d = new Dog()
d.eat(' Mm-hmm ')
d.run(100)

Generic

function createNumberArray (length: number, value: number): number[] {
  const arr = Array<number>(length).fill(value)
  return arr
}

function createStringArray (length: number, value: string): string[] {
  const arr = Array<string>(length).fill(value)
  return arr
}

function createArray<T> (length: number, value: T): T[] {
  const arr = Array<T>(length).fill(value)
  return arr
}

// const res = createNumberArray(3, 100)
// res => [100, 100, 100]

const res = createArray<string>(3, 'foo')

Some libraries don't have typescript Support , Need to download the corresponding support library .
Such as lodash, Need to install @types/lodash.

tsconfig.json File configuration details view :typescript Official website configuration description

版权声明
本文为[Charon]所创,转载请带上原文链接,感谢