首页 > 其他分享 >[Typescript] ThisType

[Typescript] ThisType

时间:2022-11-08 02:44:05浏览次数:61  
标签:Typescript obj double ThisType value half type

This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the noImplicitThis flag must be enabled to use this utility.

type Math = {
  double(): void,
  half(): void
}

const math:Math = {
  double(this: {value: number}) { // we have to tell what this is
    this.value *= 2
  },
  half(this: {value: number}) { // we have to tell what this is
    this.value /= 2
  }
}

const obj = {
  value: 1,
  ...math
}

obj.double()
console.log(obj.value)

obj.half()
console.log(obj.value)

 

We don't actually want to write this: {value: number}again and again.

 

So what we can do:

const math: Math & ThisType<{value: number}> = {
  double() {
    this.value *= 2
  },
  half() {
    this.value /= 2
  }
}

 

Two appraoch are the same, just by using Typescript utilites type ThisType<>, can simply our code.

 

标签:Typescript,obj,double,ThisType,value,half,type
From: https://www.cnblogs.com/Answer1215/p/16868035.html

相关文章

  • Typescript类型体操 - Join
    题目中文实现类型版本的Array.join,Join<T,U>接受数组T和string或者number类型U作为泛型参数,并返回U连接数组T后的字符串.EnglishImplementthetyp......
  • React中常见的TypeScript定义实战
    一引沿Fiber架构是React16中引入的新概念,目的就是解决大型React应用卡顿,React在遍历更新每一个节点的时候都不是用的真实DOM,都是采用虚拟DOM,所以可以理解成fiber就是R......
  • React-hooks+TypeScript最佳实战
    ReactHooks什么是HooksReact一直都提倡使用函数组件,但是有时候需要使用state或者其他一些功能时,只能使用类组件,因为函数组件没有实例,没有生命周期函数,只有类组件才......
  • TypeScript与JavaScript区别
    TypeScript是JavaScript的一个超集,支持ECMAScript6标准。TypeScript由微软开发的自由和开源的编程语言。TypeScript设计目标是开发大型应用,它可以编译成纯JavaS......
  • 【面试题】 那些你不知道的Typescript面试题
    1.面试官:说说你对TypeScript中类的理解?应用场景?一、是什么类(Class)是面向对象程序设计(OOP,Object-OrientedProgramming)实现信息封装的基础类是一种用户定义的引用数据类型,......
  • typescript 数据类型
    一、是什么typescript 和 javascript几乎一样,拥有相同的数据类型,另外在javascript基础上提供了更加实用的类型供开发使用在开发阶段,可以为明确的变量定义为某种类型,这......
  • [Typescript] Function scope in typescript
    Wehavethefollowingcodewhichhascompileerror:asyncfunctionreadData(event?:Event|unknown):Promise<void>{//...lettext:string|undef......
  • TypeScript常用类型(基本类型,数组类型,类型别名type ,函数类型,对象类型,接口interface,元组
    原始基本类型letage:number=18;letmyname:string="tom";letflag:boolean=true;leta:null=null;letb:undefined=undefined;letc:symbol......
  • [Typescript] 86. Medium - ToPrimitive
    Convertapropertyoftypeliteral(labeltype)toaprimitivetype.ForexampletypeX={name:'Tom',age:30,married:false,addr:{home:'12......
  • Typescript 编译模块
    Typescript有一种统一的语言处理模块的导入和导出,在编译时可以根据最终js文件应用到哪一种模块系统,根据模块系统的规范,生成代码原始Ts文件importm=require("mod");......