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 (
    <button>{title}</button>
    );
    }

    export default function MyApp() {
    return (


    Welcome to my app


    <MyButton title="I'm a button" />

    );
    }

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

相关推荐
程序员阿超的博客22 分钟前
React动态渲染:如何用map循环渲染一个列表(List)
前端·react.js·前端框架
magic 24523 分钟前
模拟 AJAX 提交 form 表单及请求头设置详解
前端·javascript·ajax
小小小小宇5 小时前
前端 Service Worker
前端
只喜欢赚钱的棉花没有糖6 小时前
http的缓存问题
前端·javascript·http
小小小小宇6 小时前
请求竞态问题统一封装
前端
loriloy6 小时前
前端资源帖
前端
源码超级联盟6 小时前
display的block和inline-block有什么区别
前端
GISer_Jing6 小时前
前端构建工具(Webpack\Vite\esbuild\Rspack)拆包能力深度解析
前端·webpack·node.js
让梦想疯狂6 小时前
开源、免费、美观的 Vue 后台管理系统模板
前端·javascript·vue.js
海云前端6 小时前
前端写简历有个很大的误区,就是夸张自己做过的东西。
前端