React项目用Typescript改造实践记录

技术栈:

  1. ant design 【支持TS语法】
  2. react
  3. react-router-dom
  4. react-redux

准备:

typescript只用来处理.ts和.tsx文件,如果配置了allowJS:true这可以处理JS文件

开始:

  • 函数组件修改
import React from 'react';

interface CompProps {
    
    
	name: string,
	children: React.ReactNode,
}
function Comp({
    
    name, children}) {
    
    
	return (
	<div>
		{
    
    name}
		{
    
    children}
	</div>
	)
}
  • hooks- useState的类型推断问题
const [isShow, setIsShow] = useState(false);
// 上面这种简单的类型typescript可以推断出来

const [manList, setManList] = useState([]);
// 上面这种对象数组,typescript无法推断出详细的类型。此时我们可以将类型作为通用参数穿进去
interface Man {
    
    
	name: string,
}
const [manList, setManList] = useState<Man[]>([]);

Hooks在Typescript中的表现

1. useState

  • 初始值不为null/undefined的话,是具备类型推导能力的,根据传入的初始值推断出类型;
  • 初始值 为null/undefined的话,需要明确传递类型定义进行约束;
  • 通过useState的第一个范型参数传入
// 可推断为string
const [name, setName] = useState('Default');

// 不可推断,需明确
// 一般情况下推荐传入类型
interface MyObj {
    
    
	name: string;
	age: number;
}
const [info, setInfo] = useState<myObj>(null);

疑问:

  1. 如下代码中,interface和type的区别是什么?推荐那种写法?
interface AA {
    
    
	name: string,
}

type AA = {
    
    
	name: string,
}

官方文档是这么介绍的:

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

但是
在进行上述类型定义的时候,没感觉两种有什么区别啊??

相同点

  • 都可以用来描述一个对象或函数
interface User {
    
    
	name: string;
}
interface SetUser {
    
    
	(name: string): void;
}

type Animal = {
    
    
	name: string,
}
type SetAnimal = (name: string) => void;
  • 都允许扩展extends
    • interface extends type ✅
    • type extends interface ✅
    • 上述两种,效果差不多,语法不同
// interface -- interface
interface Man extend User {
    
    
	age: number;
}
// type -- type
type Dog = Animal & {
    
    age: number;}

// interface -- type
interface Cat extends Animal {
    
    
	age: number;
}

// type -- interface
type Boy = User & {
    
    age: number;}

不同点-- type

  • type可以声明:基本类型的别名、联合类型、元祖等类型
// 别名
type NewName = string;

// 联合类型
type nameType = string | number

// 具体定义数组每个位置的类型
type list = [string, number, boolean]
  • 可以使用 typeof 获取实例的 类型进行赋值
// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type B = typeof div
  • 其他操作
type StringOrNumber = string | number;  
type Text = string | {
    
     text: string };  
type NameLookup = Dictionary<string, Person>;  
type Callback<T> = (data: T) => void;  
type Pair<T> = [T, T];  
type Coordinates = Pair<number>;  
type Tree<T> = T | {
    
     left: Tree<T>, right: Tree<T> };

不同点–interface

  • interface能够声明合并
    • 多次声明同一个类型,才去的措施是合并,而不是覆盖
interface Box {
    
    
	width: number;
}
interface Box {
    
    
	height: number;
}

// 实际Box为: {width, height},合并为如下:
interface Box {
    
    
	width: number;
	height: number;
}

猜你喜欢

转载自blog.csdn.net/u010682774/article/details/112679261