typescript 不是特别常用,容易忘的知识点

1、花括号对象通过方括号字符串形式取值

let obj = { name: 'asd', age: 21, salary: 400, desc: "asdasd", op: ['asd', 'as', 'qwe'] };

for (let i in obj) {
  console.log(obj[i as keyof typeof obj]);
}

let key = 'name';
console.log(obj[key as 'name']);
console.log(obj[key as keyof typeof obj]);

2、泛型约束

// 函数泛型约束
interface limit<Y> {
  value: Y[];
  length: () => number;
  join: (str?: Y) => Y;
}
// 对T约束
function fun<Y, T extends limit<Y>>(params: T): Y {
  let res: Y = params.join();
  return res;
}

// 定义对象类型
type Obj1Type = {
  value: string[],
  length: () => number,
  join: (v1?: string) => string
};
// 定义对象
const obj1: Obj1Type = {
  value: ['123', '456'],
  length() {
    return this.value.length;
  },
  join() {
    return this.value.join('');
  }
};

const result1 = fun<string, Obj1Type>(obj1);

console.log(result1);

3、枚举

enum Fruits {
  Apple,
  Orange,
  Banana,
  Peach,
  Pear,
  Watermolen
}

console.log(typeof Fruits[0], Fruits.Banana);// string, 2

enum Fruits2 {
  Apple = '123',
  Orange = 'asd',
  Banana = '123t',
  Peach = '123d',
  Pear = 'asd',
  Watermolen = 'dasd'
}

console.log(Fruits2.Banana);// 123t

enum Fruits3 {
  Apple = 10,
  Orange,
  Banana,
  Peach = '123d',
  Pear = 'asd',
  Watermolen = 'dasd'
}

console.log(Fruits3[10], Fruits3.Banana);// Apple,12

4、抽象类

abstract class Virtual {
  abstract name: string;
  abstract work(): void;
}

class Human {

}

class Man extends Human implements Virtual {
  name;

  constructor(name: string) {
    super();
    this.name = name;
  }

  work() {

  }
}

let m1 = new Man('Tom');

5、函数重载

// 函数重载
function handleData(x: string): string[];

function handleData(x: number): string;

function handleData(x: any): any {
  if (typeof x === 'string') {
    return x.split(' ');
  } else if (typeof x === 'number') {
    return String(x);
  } else {
    return 'error!';
  }
}

console.log(handleData(3),handleData('as asdd asd 34'));

6、interface定义class的类型,interface继承

class Geometry {
    setAttribute() {

    }
}
//继承后 BoxGeometryType 要实现 Geometry的属性和方法
interface BoxGeometryType extends Geometry {
    width: number;
    height: number;
    depth: number;
    clone:()=>void;
}

class BoxGeometry implements BoxGeometryType {
    width;
    height;
    depth;
    constructor(width: number, height: number, depth: number) {
        this.width = width;
        this.height = height;
        this.depth = depth;
    }

    clone(){
        
    }

    setAttribute() {

    }
}

7、构造函数的定义、继承

interface FatherType {
  name: string
  age: number;
  salary: number;
  print: () => void;
  getName: Function;
};

function Father(this: FatherType, name: string, age: number, salary: number) {
  this.name = name;
  this.age = age;
  this.salary = salary;

  this.print = function () {
    console.log(this.name, this.age, this.salary);
  }
}
Father.prototype.getName = function () {
  console.log(this.name);
}

interface SonType extends FatherType {
  name: string;
  getName: Function;
  father: () => void;
};

Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son;

function Son(this: SonType, name: string, father: { name: string, age: number, salary: number }) {
  Father.call(this, father.name, father.age, father.salary);
  this.name = name;
}

Son.prototype.getName = function () {
  console.log(this, this.name);
}

Son.prototype.father = function () {
  console.log(this);
}

const son = new (Son as any)("Tom", { name: "Tom1", age: 21, salary: 123123 });
son.father();
son.getName();

export default {};

8、修饰器

在修饰器有:类修饰器、方法修饰器、参数修饰器、属性修饰器。

执行顺序:属性>方法>参数>类 。

        1、类修饰器,可以在类上添加一些属性和方法

// example 1
const MessageDecorator: ClassDecorator = (target: Function) => {
  target.prototype.message = (msg: string) => {
    console.log(msg)
  }
}

@MessageDecorator
class Login {
  public login() {
    (this as any).message('登录成功');
    (<any>this).message('登录成功');
  }
}

new Login().login();

// example 2
function Decorate(type: string) {
  if (type == '1') {
    return (target: Function) => {
      console.log(target);
      target.prototype.p0 = () => {
        console.log('p1');
      }
    }
  } else {
    return (target: Function) => {
      target.prototype.p0 = () => {
        console.log('p2');
      }
    }
  }
}

@Decorate('1')
class P1 { }

@Decorate('2')
class P2 { }

const pa = new P1();
const pb = new P2();
(pa as any).p0();
(<any>pb).p0();

        2、 方法修饰器,可以修改被调用的函数,或者在被调用的函数调用前后做一些事情。

// example 1
const showDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
  // 修改show函数
  descriptor.value=()=>{
    console.log('function changed.');
  }
  // 在外部不可以改
  // descriptor.writable=false;
}

class User{
  @showDecorator
  public show(){
    console.log('show???');
  }
}

const u1=new User();
u1.show();

// example 2
const sleep = (time: number): MethodDecorator => {
  return (...args: any[]) => {
    const [, , descriptor] = args;
    // 保存原函数
    const method = descriptor.value;

    console.log('first');

    descriptor.value = () => {
      setTimeout(() => {
        // 在此处调用原函数
        method();
      }, time);
    }
  }
}

class Sleep {
  @sleep(1000)
  public show() {
    console.log('print something out.');
  }
}

new Sleep().show();

        3、属性修饰器,可以用来控制类中属性的获取和修改

// example 1
const property: PropertyDecorator = (target: object, propertyKey: string | symbol) => {
  let value:string;
  Object.defineProperty(target,propertyKey,{
    get:()=>{
      return value.toLowerCase();
    },
    set:(v)=>{
      value=v;
    }
  });
}

export class Hd {
  @property
  public title?: string | undefined ='123';

  public show(value) {
    this.title=value;
  }
}

const h=new Hd()
h.show("abcHAGKSDJkjnas");
console.log(h.title)


// example 2
import 'reflect-metadata'

function Inject(target: any, key: string) {
  // 根据A的类型进行实例化,并赋值到a,'design:type'自动获取固定名称,不需要自己defineMetadata
  target[key] = new (Reflect.getMetadata('design:type', target, key))();
}

class A{
  sayHello(){
    console.log('hello');
  }
}

class B {
  @Inject
  a!: A;

  say() {
    this.a.sayHello();
  }
}

new B().say();

        4、 参数修饰器,一般与方法修饰器配合使用,在调用类方法前,对方法参数进行提前处理。

导入import 'reflect-metadata'可以在修饰器之间进行传值

Reflect.defineMetadata('required', requiredParams, target, propertyKey);// 发送

 let pArray=Reflect.getMetadata('required', target, propertyKey); // 接收

import 'reflect-metadata'

const params: ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => {
  let requiredParams: number[] = [];
 
 requiredParams.push(parameterIndex);
 
  Reflect.defineMetadata('required', requiredParams, target, propertyKey)
}

const validate: MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
  console.log( 'method decorate params =',target, propertyKey,descriptor);

  let pArray=Reflect.getMetadata('required', target, propertyKey);

  console.log(pArray);

  const method=descriptor.value;

  descriptor.value=(...args)=>{

    console.log('args=',args,'pArray=',pArray);
    for(let i in pArray){
      args[pArray[i]]+='!!!';
    }

    method(...args);
  }

}

export class User {
  @validate
  public find(@params name: string,age:number) {
    console.log(name,age);
  }
};

new User().find("abcdef",21); // abcdef!!! 21!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/594786.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

通过自适应提示提升大语言模型的零样本推理能力

随着大模型&#xff08;LLMs&#xff09;的快速发展&#xff0c;它们在自然语言处理&#xff08;NLP&#xff09;任务上取得了前所未有的成就。特别是&#xff0c;LLMs展现出了强大的推理和规划能力&#xff0c;这得益于它们的少样本和零样本学习能力。然而&#xff0c;现有的方…

三分钟一条抖音爆款短视频,轻松日引500+创业粉,复制粘贴即可,简单好…

详情介绍 团队历经三个月终于给兄弟把这个抖音测试出来了过程就不说了全是泪 最近抖音拆解项目是比较火的&#xff0c;前段时间不行拉现在又是可以继续拆解拉我这边自己也实操的一个引流渠道 咱们为什么要通过抖音来引流创业粉啊 因为抖音和知乎的创业粉的质量还是比较高的 本次…

【SQL每日一练】统计复旦用户8月练题情况

文章目录 题目一、分析二、题解1.使用case...when..then2.使用if 题目 现在运营想要了解复旦大学的每个用户在8月份练习的总题目数和回答正确的题目数情况&#xff0c;请取出相应明细数据&#xff0c;对于在8月份没有练习过的用户&#xff0c;答题数结果返回0. 示例代码&am…

线程安全的概念及原因

1.观察线程不安全 public class ThreadDemo {static class Counter {public int count 0;void increase() {count;}}public static void main(String[] args) throws InterruptedException {final Counter counter new Counter();Thread t1 new Thread(() -> {for (int …

腾讯云服务器之ssh远程连接登录

一、创建密钥绑定实例 创建密钥会自动下载一个私钥&#xff0c;把这个私钥复制到c盘 二、设置私钥权限 1、删除所有用户权限 2、添加当前用户权限 查看当前用户名 echo %USERNAME%三、ssh远程连接到服务器 ssh ubuntu175.xxx.xxx.112 -i C:\Crack\cs2.pem四、修改root密码 s…

构建第一个ArkTS应用之@LocalStorage:页面级UI状态存储

LocalStorage是页面级的UI状态存储&#xff0c;通过Entry装饰器接收的参数可以在页面内共享同一个LocalStorage实例。LocalStorage也可以在UIAbility实例内&#xff0c;在页面间共享状态。 本文仅介绍LocalStorage使用场景和相关的装饰器&#xff1a;LocalStorageProp和LocalS…

修改JupyterNotebook文件存储位置

Jupyter Notebook 1、通过AnaConda安装Jupyter Notebok 2、在开始菜单里找到并打开Anaconda Prompt&#xff0c;输入如下命令&#xff0c;然后执行。 jupyter notebook --generate-config4、打开以下文件 找到 C:/Userzh/.../.jupyter 打开 jupyter_notebook_config.py 取消…

信息系统项目管理师——第20章高级项目管理

本章是将第三版的第20章、第21章、第18章、第25章、第2章的PRINCE2进行了合并&#xff0c;精简和新增了部分知识。选择、案例都会考。从2023年上半年考情来看 选择题&#xff0c;考3-4分&#xff0c;基本是课本原话&#xff0c;但是知识点比较分散&#xff0c;需要多刷题&#…

HTML5实现酷炫个人产品推广、工具推广、信息推广、个人主页、个人介绍、酷炫官网、门户网站模板源码

文章目录 1.设计来源1.1 主界面1.2 我的产品界面1.3 关于我们界面1.4 照片墙界面1.5 发展历程界面1.6 优秀人才界面1.7 热门产品界面1.8 联系我们界面 2.灵活调整模块3.效果和源码3.1 动态效果3.2 源代码 源码下载 作者&#xff1a;xcLeigh 文章地址&#xff1a;https://blog.c…

python中怎么清屏

一、“Windows命令行窗口”下清屏&#xff0c;可用下面两种方法&#xff1a; 第一种方法&#xff0c;在命令行窗口输入&#xff1a; import os ios.system("cls") 第二种方法&#xff0c;在命令行窗口输入&#xff1a; import subprocess isubprocess.call("cl…

Rust语言系统编程实战(小北学习笔记)

前言 进入大学以来&#xff08;计算机应用技术——大数据方向&#xff09;&#xff0c;就像很多程序猿&#x1f412;一样&#xff0c;小北开始每学期学习一种新的编程语言。通过学习另一个编程语言&#xff0c;可以了解很多规范和规则&#xff0c;并得到了一些想法&#xff0c;…

Wireshark CLI | 过滤包含特定字符串的流

问题背景 源自于和朋友的一次技术讨论&#xff0c;关于 Wireshark 如何查找特定字符串所在的 TCP 流&#xff0c;原始问题如下&#xff1a; 仔细琢磨了下&#xff0c;基于我对 Wireshark 的使用经验&#xff0c;感觉一步到位实现比较困难&#xff0c;所以想着说用 Wireshark C…

【C语言】解决不同场景字符串问题:巧妙运用字符串函数

&#x1f308;个人主页&#xff1a;是店小二呀 &#x1f308;C语言笔记专栏&#xff1a;C语言笔记 &#x1f308;C笔记专栏&#xff1a; C笔记 &#x1f308;喜欢的诗句:无人扶我青云志 我自踏雪至山巅 文章目录 一、字符函数1.1 字符分类函数1.1.1 islower1.1.2 isupper 1.…

Android中TabLayout与ViewPager结合使用生命周期详解

博主前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住也分享一下给大家&#xff0c; &#x1f449;点击跳转到教程 效果 使用的布局如下&#xff1a; <?xml version"1.0" encoding"utf-8"?> …

踏准芯片定制风口的灿芯股份,护城河足够深吗?

近年来&#xff0c;芯片定制渐成风潮&#xff0c;不仅位于下游、自身有巨大芯片需求的科技巨头如谷歌、OpenAI等纷纷转向定制&#xff0c;而且产业中游主打标准化芯片的主流芯片设计公司如博通、英伟达等&#xff0c;也相继开辟或加码定制业务。 风潮背后&#xff0c;一方面是…

【JavaEE网络】从数据链路层到应用层的DNS

目录 数据链路层以太网 DNS 数据链路层 越往下与程序员越远 代表协议&#xff1a;以太网。平常用的网线也叫“以太网线”&#xff0c;平常用的交换机也叫“以太网交换机” 以太网 认识以太网 “以太网” 不是一种具体的网络&#xff0c;而是一种技术标准&#xff1b;既包含…

Git笔记-常用指令

Git笔记-常用指令 一、概述二、仓库管理二、缓存区操作1. 添加文件到缓存区2. 取消缓存文件3. 忽略列表 三、日志状态信息四、分支操作五、六、 一、概述 这里记录一些git常用的指令。 二、仓库管理 # 本地仓库初始化 git init# 克隆仓库 git clone git_url # git clone ht…

Unity之ShaderGraph入门简介与配置

前言 ShaderGraph是Unity的一个可视化着色器编辑工具,它允许开发者在不编写代码的情况下创建复杂的着色器效果。ShaderGraph提供了一个直观的图形界面,用户可以通过拖拽节点并连接它们来构建自定义的着色器。用户可以在ShaderGraph中使用各种节点,如数学运算、纹理采样、颜…

亚马逊Lazada速卖通卖家必备:利用自养号测评提升店铺排名与销量

Wish与亚马逊、速卖通、eBay等知名的跨境电商平台有所区别&#xff0c;它专注于移动端市场。对于许多初次涉足跨境电商领域的新手卖家而言&#xff0c;他们往往困惑于如何在Wish上起步&#xff0c;因为该平台的运营模式与其他平台有所不同。Wish是一款基于手机端App的跨境电商平…

TypeScript 基础学习笔记:interface 与 type 的异同

TypeScript 学习笔记&#xff1a;interface 与 type 的异同 &#x1f3a3; 引言 在 TypeScript的世界里&#xff0c;精准的类型定义是保证代码质量与团队协作效率的关键。interface 和 type 作为两种核心的类型定义工具&#xff0c;它们各自承载着不同的设计意图与应用场景。本…
最新文章