标签 TypeScript 下的文章

// 类型别名
let sum: (x: number, y: number) => number
const result = sum(1, 2)

type PlusType = (x: number, y: number) => number
let sum2: PlusType
const result2 = sum2(2, 3)

// 联合类型
type StrOrNum = string | number
let result3: StrOrNum = '123'
result3 = 123
let union = 1  | 2 | 3 | 4
// 字面量
const str: 'name' = 'name'
const number: 1 = 1


type Directions = 'Up' | 'Down' | 'Left' | 'Right'
let toWhere: Directions = 'Right'
// 交叉类型
interface IName {
  name: string
}
type IPerson = IName & {age: number}
let person: IPerson = { name: 'my name', age: 123 }


// 泛型
function identity<T>(arg: T): T {
  return arg;
}
let result1 = identity<string>("str");
let result2 = identity("str");
let result3 = identity(123)
let result4 = identity(false)

// 元组
function swap<T, U>(tuple: [T, U]): [U, T] {
  return [tuple[1], tuple[0]]
}
let arr1 = swap<string, number>(['str', 1])
let arr2 = swap(['str', 1])
let arr3 = swap([1, 'str'])

// 数组
function echoWithArr<T>(arg: T[]): T[] {
  return arg
}

let arr4 = echoWithArr<string>(['str1', 'str2'])
let arr5 = echoWithArr<number>([1, 2])
let arr6 = echoWithArr<number | string>([1, 'str'])
let arr7 = echoWithArr([1, 2])
let arr8 = echoWithArr(['str1', 'str2'])
let arr9 = echoWithArr([1, 'str'])

// 属性约束
interface IwithLength {
  length: number
}

function echoWithLength<T extends IwithLength>(arg: T): T {
  console.log(arg.length)
  return arg
}

let str1 = echoWithLength('str')
let obj1 = echoWithLength({ length: 10 })
let arr10 = echoWithLength([1, 2, 3, 4])

// 类
class Queue<T> {
  private data = [];
  push(item: T) {
    return this.data.push(item)
  }
  pop(): T {
    return this.data.shift()
  }
}

const queue1 = new Queue<number>()
const queue2 = new Queue<string>()

// 接口
interface KeyPair<T, U> {
  key: T
  value: U
}

let kp1: KeyPair<number, string> = { key: 1, value: "str" }
let kp2: KeyPair<string, number> = { key: "str", value: 1 }
let arr11: Array<number> = [1, 2, 3]
let arr12: Array<string> = ['s1', 's2', 's3']