ReactJS中使用TypeScript

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});
    }
    };

  2. 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 name
    animation: T;  // Generic property for the animal's animation

    constructor(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 (

    );
    }

    export default function MyApp() {
    return (


    Welcome to my app




    );
    }

  2. 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 (

    );
    }

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 的灵活性和动态性,开销效率降低不少,如果做的是类库,还要有类型定义文件,看个人喜好和项目需求吧。

相关推荐
梨子同志19 分钟前
qiankun
前端
梨子同志28 分钟前
Nginx
前端
梨子同志29 分钟前
NestJS
前端
梨子同志1 小时前
Next.js
前端
谭光志1 小时前
工具塞满上下文窗口怎么办?深度拆解 AI Agent Tool Search 按需加载实现原理
前端·后端·ai编程
Hilaku1 小时前
前端架构师的克制:什么时候该坚决对新技术说不?
前端·javascript·程序员
陈随易1 小时前
前端项目部署只要30秒
前端·后端·程序员
本末倒置1831 小时前
从 Vue CLI 迁移到 Rsbuild 后,JSX 突然全挂了?一次排查记录
前端
古夕1 小时前
多应用同域部署下 Favicon 异常问题排查与治理
前端·javascript
YIAN1 小时前
从零手写文件读取 MCP 服务:一文吃透 Model Context Protocol 全链路通信原理
前端·后端·mcp