ReactJS中使用TypeScript

发布于:2024-04-28 ⋅ 阅读:(21) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到