亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【九月打卡】第47天 TypeScript(3)

標簽:
Typescript

复杂函数类型扩展

有属性的函数类型定义

interface FunWithAttr {
  name: string,
  (val: string): void
}

const test: FunWithAttr = (val: string) => {
  console.log(val)
}
test.name = 'tz'

构造函数类型定义

interface ClassType {
  new (name: string) : void;
}

function test(OuterClass: ClassType) {
  const ins = new OuterClass('tz')
}

class Test {
  name: string;
  constructor(str: string) {
    this.name = str
  }
}

Date的类型定义

interface DateType {
  new (): Date;
  (datestring: string): string
}

函数和泛型

function getFirst<T>(arr: T[]): T {
  return arr[0]
}

const arr = [1, 2, 3]
const res = getFirst(arr)

const arr1 = ['a', 'b', 'c']
const res1 = getFirst(arr1)

函数重载
对函数不同情况做类型定义(包含定义和实现)

// 函数类型定义
function getString(str: string): void;
function getString(str: string, str1: string): number;

// 函数实现
function getString(str: string, str1?: string){
  if(typeof str1 === 'string'){
    return (str+str1).length
  }
  return str;
}

对象类型扩展

对象的解构和类型定义要分开

// 解构
function showPerson({ name: nick = 'tz', age: old = 18 }) {
  console.log(nick);
  console.log(old);
}

// TS类型定义
function showPerson({ name, age}: {name: string, age: number}) {
  console.log(name);
  console.log(age);
}

interface的readonly属性
readonly可以将属性变成只读,不可以修改

interface Person {
  readonly name: string;
  age: number;
}

const student: Person = {name: 'tz', age: 18}
student.name = '123'  // 会报错,不可以修改

对象扩展属性
对于对象中若干不确定的对象,可以使用扩展属性

interface User {
  name: string;
  [key: string]: string | number;  // 扩展属性, key可以任意写
  
}

const user: User = {
  name: 'tz',
  age: 18,
  avatar: '',
  sex: 'male'
}

对象类型的继承

interface通过extends来继承

interface Animal {
  name: string;
  age: number;
  breath: () => void;
}

interface Dog extends Animal {
  bark: () => void
}

const dog: Dog = {
  name: 'dog',
  age: 1,
  breath: () => {},
  bark: () => {}
}

多个对象进行集成

  • 通过extends继承多个类型,类型之间用逗号隔开
interface Circle {
  radius: number;
}
interface Color {
  color: string;
}
interface ColorfulCircle extends Circle, Color {}
const colorfulCircle: ColorfulCircle = {
  radius: 13,
  color: '#fff'
}
  • 使用交叉类型来实现集成
interface Circle {
  radius: number;
}
interface Color {
  color: string;
}
type ColorfulCircle = Circle & Color;
const colorfulCircle: ColorfulCircle = {
  radius: 13,
  color: '#fff'
}

小结

函数类型扩展

  • 有属性的函数类型定义
  • 构造函数类型定义
  • Date的类型定义
  • 函数中的泛型使用
  • 函数重载(包括定义和实现)

对象类型扩展

  • 对象的解构和类型定义要区分开
  • interface的readonly属性(属性只读,不可以修改)
  • 对象的扩展属性类型定义(使用[])
  • 对象类型的继承
  • 多个对象的集成(使用extentds 或者交叉类型)
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消