typescript 学习笔记

// 如果代码里有 import export,那么这个文件就变成模块
export { }
// const root = document.getElementById('app')
// 断言
// root!.style.color = 'pink'; ! 断言不为空
// (root as HTMLElement).style.color = 'pink';
// (<HTMLElement>root).style.color = 'pink'

type GetUsreName = (firstName: string, lastName: string) => string
const gameName: GetUsreName = (firstName: string, lastName: string): string => {
  return firstName + lastName
}

namespace a {
  interface Person {
    ast: number
  }
  function func(target: any) {
    target.prototype.ast = 18
  }
  @func
  class Person {
    // name: string
    // constructor(name: string) {
    //   this.name = name
    // }
    constructor(public name: string) { }
    // constructor(public readonly name: string){}
    get rename() {
      return this.name
    }
    set rename(name) {
      this.name = name
    }
  }
  console.log((new Person('张三')).ast)
}

namespace b {
  interface Person {
    gender: number
  }
  function enhancer(target: any) {
    return class Child extends target {
      public name: string = ''
      public gender: number = 10
      constructor(name: string) {
        super(name)
      }
    }
  }
  @enhancer
  class Person {
    public name: string
    constructor(name: string) {
      this.name = name
    }
  }
  console.log((new Person('张三')).gender)
}

namespace c {
  function uperCase(target: any, propertyName: string) {
    let value = target[propertyName]
    const getter = () => value
    const setter = (newValue: string) => {
      value = newValue.toUpperCase()
    }
    delete target[propertyName]
    Object.defineProperty(target, propertyName, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true
      // 设置 getter setter 后不能设置 value 或者 writable
    })
  }
  class Person {
    // 装饰属性 两个参数
    @uperCase
    name: string
    constructor(name: string) {
      this.name = name
    }
  }
  console.log(new Person('abc').name)
}

namespace d {
  function changeFun(target: any, propertyName: string, descriptor: any) {
    console.log(descriptor)
  }
  function toNumber(target: any, propertyName: string, descriptor: any) {
    const value = descriptor.value
    descriptor.value = function (...args: string[]) {
      const numberArr: Array<number> = args.map(item => parseInt(item))
      value.apply(this, numberArr)
    }
  }
  function add(target: any, methodName: string, paramsIndex: number) {

  }
  class Person {
    name: string = '张三'
    // 装饰属性 三个参数
    @changeFun
    eat() {
    }
    @toNumber
    login(id: string, pas: string) {
      console.log(typeof id)
    }
    toLogin(id: number, @add pas: number) {
      console.log(id + pas)
    }
  }
  const person = new Person()
  person.login('1', '2')
  person.toLogin(1, 2)
}

// 执行顺序 1. 属性方法 2. 方法参数 3.类 同一个有多个装饰器从后向前执行


abstract class Animal {
  name: string = '张三'
  abstract getName(): string
}
class Cat extends Animal {
  name: string = '李四' // 可以不继承
  getName(): string { // 必须继承
    return this.name
  }
}


interface Point {
  x: number,
  y: number
}
let point: Point = {
  x: 15,
  y: 16
}

namespace e {
  interface Speakable {
    speak(): void
  }

  interface Eatable {
    eat(): void
  }
  interface Drinkable extends Eatable {
    drink(): void,
    readonly age: number
  }
  interface Discount {
    (price: number): number
  }
  interface UserInfo {
    [age: number]: string
  }
  class Person implements Speakable, Drinkable {
    age: number = 15
    speak() { }
    eat() { }
    drink() { }
  }
  let discount: Discount = (price: number) => {
    return price * 0.5
  }
  let user1: UserInfo = {
    1: '张三'
  }
  let user2: UserInfo = ['张三']

  // 接口约束类
  class Animal {
    age: number = 1
  }
  interface WithClass {
    new(name: string): Animal
  }
  function createAnimal(clas: WithClass, name: string) {
    return new clas(name)
  }
  const animal = createAnimal(Animal, '')
}


namespace f {

  interface Calculate {
    <T>(a: T, b: T): T
  }
  let result1: Calculate = function <T>(a: T, b: T): T {
    return a
  }
  let result2: Calculate = <T>(a: T, b: T): T => {
    return a
  }
  result1<number>(1, 2)
  // --------------------------------
  interface Calculate2<T> {
    (a: T, b: T): T
  }
  let result3: Calculate2<number> = <T>(a: T, b: T): T => {
    return a
  }
  result3(1, 2)

  // 默认泛型
  function createAge<T = number>(name: string, age: T): T | null {
    return age || null
  }
  createAge<string>('', '')

  // 泛型约束
  interface SetLength {
    length: number
  }
  function logger<T extends SetLength>(str: T): number {
    return str.length
  }

  // 泛型类型别名
  type Cart<T> = {
    list: T[]
  } | T[]
  let cart: Cart<number> = {
    list: [1, 2]
  }
  let cart2: Cart<string> = ['1', '2']
  // interface 是一个真正的类型
  // type 定义类型别名,并不是真正的类型
  // 也可以继承和实现
  interface Cart2 {
    a: number
  }
  type SCart2 = Cart2

  interface Cart3 extends SCart2 {
    b: number
  }
  let cart3: Cart3 = {
    a: 1,
    b: 2
  }
  class Cart4 implements SCart2 {
    a: number = 1
  }
}

namespace g {
  // 基本类型兼容性
  let num: number | string = 1
  let str: string = ''
  num = str

  // 类兼容性
  class Person {
    name: string
    age: number
    constructor(name: string, age: number) {
      this.name = name
      this.age = age
    }
  }
  let per: Person = new Person('', 1)
  // 不能多属性必须和类属性一致
  per = {
    name: '张三',
    age: 18
  }

  // 函数兼容性
  type Sum = (a: number, b: string) => number
  let func = (a: number, b: string): number => {
    return a
  }
  let sum: Sum
  sum = func

  let func1 = (a: number): number => { // 参数可以少不能多
    return a
  }
  sum = func1

  // 函数返回值
  type Return = () => { name: string, age: number }
  let funr: Return = () => {
    return { name: '', age: 1 }
  }
  let funr2: Return = () => {
    return { name: '', age: 1, home: '' } // 多了可以 少了不行
  }

  // 泛型兼容
  interface Empty<T> {
    data: T
  }
  let emp!: Empty<string>
  let emp2!: Empty<number>
  // emp = emp2  不能将 number 类型赋值给 string

  // 枚举兼容性
  enum Colors {
    Red, Yellow = 'gg'
  }
  let color: string
  color = Colors.Yellow
}


namespace h {
  // 类型保护
  function checkType(arg: number | string | boolean): void {
    if (typeof arg === 'number') {
      arg.toFixed()
    } else if (typeof arg === 'string') {
      arg.trim()
    } else {
    }
  }

  class Animal {
    public name: string = ''
  }
  class Dog extends Animal {
    public leg: number = 4
  }
  function getNmae(a: Animal) {
    if (a instanceof Dog) {
      a.leg
    } else {
      a.name
    }
  }


  function checkString(a: string | null) {
    // if(a === null) {
    //   a = ''
    // }
    function ensure() {
      a = a || '' // 无法识别 需要断言
    }
    ensure()
    a!.charAt(0) // 非空断言
  }


  interface Types1 {
    class: 'warning',
    text1: '修改'
  }
  interface Types2 {
    class: 'error',
    text2: '删除'
  }
  function getType(a: Types1 | Types2) {
    if (a.class === 'warning') {
      a.text1
    } else {
      a.text2
    }
  }


  interface Birds {
    swing: number
  }
  interface DOgs {
    leg: number
  }
  function getNumber(a: Birds | DOgs) {
    if ('swing' in a) {
      a.swing
    } else {
      a.leg
    }
  }


  //  自定义类型保护
  interface Birds2 {
    name1: 'bird',
    leg: number
  }
  interface DOgs2 {
    name2: 'dog',
    leg: string
  }

  function isBird(a: Birds2 | DOgs2): a is Birds2 {
    return a.leg === 2
  }
  function getAnimal(a: Birds2 | DOgs2) {
    if (isBird(a)) {
      a.name1
    } else {
      a.name2
    }
  }
  let birds: Birds2 = {
    name1: 'bird',
    leg: 2
  }
  getAnimal(birds)
}

namespace i {
  // 交叉类型
  interface Bird {
    name: string,
    fly(): void
  }
  interface Person {
    name: string,
    eat(): void
  }
  type BridPer = Bird & Person
  let person: BridPer = {
    name: '张三',
    fly() { },
    eat() { }
  }

  // 索引访问操作符
  interface Person2 {
    name: string,
    age: number,
    job: {
      name: string
    },
    interests: {
      name: string,
      level: number
    }[]
  }
  let person2: Person2['job']['name'] = ''
  let level: Person2['interests'][0]['level'] = 10


  // keyof 索引类型查询操作符
  interface Person3 {
    name: string,
    age: number,
    gender: 'male' | 'female'
  }
  // type Person3Keys = 'name' | 'age' | 'gender'
  type Person3Keys = keyof Person3
  function getValueByKey(val: Person3, key: Person3Keys) {
    val[key]
  }
  let person3: Person3 = {
    name: '张三',
    age: 15,
    gender: 'male'
  }
  getValueByKey(person3, 'name')



  // 映射类型
  interface Person4 {
    name: string,
    age: number,
    gender: 'male' | 'female'
  }
  // type PartialPerson = {
  //   [key in keyof Person4]?: Person4[key]
  // }
  type Partial<T> = {
    [key in keyof T]?: T[key]
  }
  type PartialPerson = Partial<Person4>



  interface Person5 {
    name?: string,
    age?: number,
    gender?: 'male' | 'female'
  }
  type Required<T> = {
    [key in keyof T]-?: T[key] // 可选变必填
  }
  type AddRequired<T> = {
    [key in keyof T]+?: T[key]  // 增加可选
  }
  type RequiredPerson5 = Required<Person5>



  interface Person6 {
    name: string,
    age: number,
    gender: 'male' | 'female'
  }
  type Readonly<T> = {
    readonly [key in keyof T]: T[key] // 可选变必填
  }
  type ReadonlyPerson6 = Readonly<Person6>



  interface Person7 {
    name: string,
    age: number,
    gender: 'male' | 'female'
  }
  type Pick<T, K extends keyof T> = {
    [key in K]: T[K]
  }
  type PickPerson7 = Pick<Person7, 'name'>
  let person7: PickPerson7 = { name: '' }



  type Exc = Exclude<string | number, string> // 去掉某个类型
  let esc: Exc = 1

  type Ext = Extract<string | number | null, string> // 只留下某个类型
  let ext: Ext = ''

  type NonNull = NonNullable<string | number | undefined | null> // 去掉 null 和 undefined
  let nonul: NonNull = 1

  function getReturn() {
    return { name: '', age: 18 }
  }
  type UserInfo = ReturnType<typeof getReturn>
  let userinfo: UserInfo = { name: '', age: 15 }


  class Person8 {
    name: string
    constructor(name: string) {
      this.name = name
    }
  }
  type Pser8 = InstanceType<typeof Person8>
  let person8: Pser8 = new Person8('')
}


namespace j {
  interface Water {
    name: string
  }
  interface Fish {
    name1: string
  }
  interface Fish2 {
    name1: string,
    age: number
  }
  interface Brid {
    name2: string
  }
  interface Sky {
    name3: string
  }
  //  T 继承 Fish 根据属性判断是否为 true, 可多不可少
  type Condition<T> = T extends Fish ? Water : Sky
  let condition: Condition<Fish2> = {
    name: ''
  }
  let condition2: Condition<Fish | Brid> = {
    name: '',
    name3: ''
  }
  export class Person {
    constructor(public name: string) { }
  }
}
(new j.Person('')).name





namespace h {
  declare const $: (selector: string) => {
    click(): void
    with(): void
  }

  declare enum Season {
    Spring,
    Summber,
    Autumn,
    Winter
  }

  let season: Season[] = [
    Season.Spring,
    Season.Summber,
    Season.Autumn,
    Season.Winter
  ]


  declare namespace jQuery{
    function ajax(url: string, config: any): void
    let name: string
    namespace fn {
      function extend(obj: any): void
    }
  }
  jQuery.ajax('/api', {})
  jQuery.name
  jQuery.fn.extend
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,000评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,745评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,561评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,782评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,798评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,394评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,952评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,852评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,409评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,483评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,615评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,303评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,979评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,470评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,571评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,041评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,630评论 2 359