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。
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}`);
}
};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。
代码中{ 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>
);
}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 的灵活性和动态性,开销效率降低不少,如果做的是类库,还要有类型定义文件,看个人喜好和项目需求吧。
到此这篇关于reactjs中使用typescript的文章就介绍到这了,更多相关reactjs使用typescript内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论