ReactJS中使用TypeScript

embedded/2024/10/21 5:34:38/

TypeScript

TypeScript 实际上就是具有强类型的 JavaScript,可以对类型进行强校验,好处是代码阅读起来比较清晰,代码类型出现问题时,在编译时就可以发现,而不会在运行时由于类型的错误而导致报错。但是,从某种程度说TypeScript 失去了 JavaScript 动态语言的灵活性,代码写起来也会比较繁琐,需要生命类型。

主要语法

首先,TypeScript 支持 JavaScript基本写法,主要特性是加了类型,主要看下相对于 JavaScript 比较特殊的几种写法。

参数加类型

主流的强类型语言在函数中都是要定义参数类型的,如下,useName 的类型是字符串。

function greet(userName: string): string {return `Hello, ${user.name}! You are ${user.age} years old.`;
}
Type 和 Interface

Type主要用于定义类型。Interface 主要用于定义接口,Interface 可以被扩展、可以被类继承。语法上 Type 和 Interface 可以互换,都可以仅当类型试用。但是,项目开发中,尽量不要混用,定义类型时就用 Type,定义接口时就用 Interface。

  1. Type 试用方法
type Animal = {name: string;species: string;
};type Loggable = {log(): void;
};type LoggableAnimal = Animal & Loggable; //合并const dog: LoggableAnimal = {name: "Buddy",species: "Canine",log() {console.log(`${this.name} is a ${this.species}`);}
};
  1. Interface 试用方法
interface Person {name: string;age: number;introduce(): string;
}class Student implements Person {name: string;age: number;course: string;constructor(name: string, age: number, course: string) {this.name = name;this.age = age;this.course = course;}introduce(): string {return `Hi, I'm ${this.name}, and I'm ${this.age} years old. I study ${this.course}.`;}
}

泛型

泛型是 TypeScript 非常重要的概念,在 React 中使用非常多。什么是泛型,简单理解就是类型参数化,例如在 Animal 类中,有一个animal 属性,这个属性可以是 Cat或者Dog,不用泛型的话,可能要定义多个类,当然也可以使用接口或者父类进行抽象。有了泛型,只要通过泛型传递就可以了。

class Animal<T> {name: string; // Regular property for the animal's nameanimation: T;  // Generic property for the animal's animationconstructor(name: string, animation: T) {this.name = name;this.animation = animation;}animate(): void {console.log(`The ${this.name} starts to: ${this.animation}`);}
}

TypeScript 中方法和类型也可以试用泛型。

#方法泛型
function createPair<S, T>(v1: S, v2: T): [S, T] {return [v1, v2];
}
console.log(createPair<string, number>('hello', 42)); // ['hello', 42]#类型泛型
type Wrapped<T> = { value: T };const wrappedValue: Wrapped<number> = { value: 10 };

TypeScript 上手很快难度不大,做个基本了解,就可以开始使用了,就是写起来麻烦一些。

React 中使用 TypeScript

在 React 中使用 TypeScript 最重要的就是类型,例如,props 都有什么字段,字段都是什么类型。只要是在Typescript 中出现的对象,就必要有对应的类型,TypeScript 中如果不指定类型,如果是简单类型可以自动解析,如果是函数参数默认为 Any。

  1. 代码中{ title: string } 是行内类型
function MyButton({ title }: { title: string }) {return (<button>{title}</button>);
}export default function MyApp() {return (<div><h1>Welcome to my app</h1><MyButton title="I'm a button" /></div>);
}
  1. MyButtonProps 是单独定义的类型
interface MyButtonProps {/** The text to display inside the button */title: string;/** Whether the button can be interacted with */disabled: boolean;
}function MyButton({ title, disabled }: MyButtonProps) {return (<button disabled={disabled}>{title}</button>);
}

Hooks

React hooks 使用 TypeScript 主要用到的就是泛型,例如,useState

#自动解析为 bool
const [enabled, setEnabled] = useState(false);#指定类型为Status
type Status = "idle" | "loading" | "success" | "error";
const [status, setStatus] = useState<Status>("idle");

Dom Event

DomEvent 是转换到 TypeScript 之后比较难上手的,需要熟悉一下 React 的类型定义。这个有个办法就是通过 inline 方法,然后VsCode 会给你提示。

export default function Form() {const [value, setValue] = useState("Change me");function handleChange(event: React.ChangeEvent<HTMLInputElement>) {setValue(event.currentTarget.value);}return (<><input value={value} onChange={handleChange} /><p>Value: {value}</p></>);
}

直接复制事件类型就可以。
在这里插入图片描述
个人觉得 TypeScript 虽然现在都在推广,但是确实失去了JavaScript 的灵活性和动态性,开销效率降低不少,如果做的是类库,还要有类型定义文件,看个人喜好和项目需求吧。


http://www.ppmy.cn/embedded/19716.html

相关文章

从零开始:UniApp 项目搭建指南

正文&#xff1a; 在移动应用开发领域&#xff0c;UniApp 作为一款基于 Vue.js 的跨平台框架&#xff0c;为开发者提供了更加便捷的方式来构建同时支持多个平台的应用程序。本文将带领你从零开始&#xff0c;一步步地搭建一个 UniApp 项目&#xff0c;并介绍其中的关键步骤和注…

代码随想录(番外)图论2

代码随想录&#xff08;番外&#xff09;图论2 4. 岛屿数量.深搜版 5. 岛屿数量.广搜版 6. 岛屿的最大面积 https://programmercarl.com/0200.%E5%B2%9B%E5%B1%BF%E6%95%B0%E9%87%8F.%E6%B7%B1%E6%90%9C%E7%89%88.html 4. 岛屿数量.深搜版 class Solution { public:int dir[4…

ZYNQ--PL读写PS端DDR数据

PL 和PS的高效交互是zynq 7000 soc开发的重中之重,我们常常需要将PL端的大量数 据实时送到PS端处理,或者将PS端处理结果实时送到PL端处理,常规我们会想到使用DMA 的方式来进行,但是各种协议非常麻烦,灵活性也比较差,本节课程讲解如何直接通过AXI总 线来读写PS端ddr的数据…

再谈C语言——理解指针(二)

指针变量类型的意义 指针变量的⼤⼩和类型⽆关&#xff0c;只要是指针变量&#xff0c;在同⼀个平台下&#xff0c;⼤⼩都是⼀样的&#xff0c;为什么还要有各种各样的指针类型呢&#xff1f; 其实指针类型是有特殊意义的&#xff0c;我们接下来继续学习。 指针的解引⽤ 对⽐…

实时通讯技术 WebRTC 介绍

WebRTC WebRTC&#xff08;Web Real-Time Communication&#xff09;是一个支持网页浏览器进行实时语音对话或视频对话的技术。 历史 2010年5月&#xff0c;Google以6820万美元收购VoIP软件开发商Global IP Solutions的GIPS引擎&#xff0c;并改为名为“WebRTC”。WebRTC使用…

【快速入门 LVGL】-- 5、Gui Guider界面移植到STM32工程

上篇&#xff0c;我们已学习&#xff1a;【快速入门 LVGL】-- 4、显示中文 工程中添加了两个按钮作示范。运行效果如图&#xff1a; 本篇&#xff1a;把Gui Guider设计好的界面&#xff0c;移植到STM32工程。 特别地&#xff1a; 在使用Gui Guider进行界面设计时&#xff0c;应…

Element-plus使用记录

Element-plus使用中遇到的问题与解决方案 动态渲染icon Element-plus中的icon需要单独安装Icon 图标 | Element Plus <template><div class"page"><div class"h-menu"><div class"show-menu" click"isCollapseHandle&…

QT-真正的成员函数

真正的成员函数不需要传递参数就可以实现对成员数据的操作&#xff0c;区别于使用结构体中的变量进行操作&#xff0c;使代码更加简洁 #include <stdio.h>#include <stdlib.h>#include <string>#include <iostream>using namespace std;class Car{ …