1.TypeScript优势:
JS的超集,JS有的TS都有,能运行JS就能运行TS
强大的类型系统提升了代码的可阅读性、可维护性
类型推断、类型检查、代码提示
有利于在团队中推动严格的代码检查
2.项目配置TypeScript
- 安装TypeScript
npm install --save-dev typescript
- 生成tsconfig.json
tsc --init
- 安装类型申明(众多)
npm i --save-dev @types/react
npm i --save-dev @types/react-native
3.基础类型的使用方法
- 数值类型:number
- 字符串类型:string
- 布尔类型:boolean
4.区分数组元祖和枚举类型
5.函数类型
基础的函数申明
函数参数类型和返回值类型的申明
函数的可选参数和默认参数
6.使用命名空间和类型文件
局部类型文件和全局类型文件
使用类型文件中的类型定义数据
新建ts文件夹,新建TsDemo.tsx文件,代码如下:
import { Button, StyleSheet, View } from "react-native"
export default () => {
const add = (n1: number, n2: number) : number => {
return n1 + n2;
}
const onButtonPress: () => void = () => {
const num1: number = 123
const num2: number = 12.34
console.log(add(num1, num2))
const num3: Number = new Number(13)
console.log(num3.valueOf())
const s1: string = "Hello"
const b1: boolean = true
const b2: boolean = !s1; //true
//数组类型
const a1: Array<number> = [1, 2, 3, 4, 5];
const a2: number[] = [1, 2, 3, 4, 5];
const a3: Array<number> = new Array(5);
const a4: Array<number | string> = new Array();
//元祖类型
const t1: [string, number, boolean] = ["张三", 12, true];
//枚举类型
enum Job {
Teacher = "老师",
Programmer = "程序员",
Cook = "厨师"
}
}
//函数类型
const f1: (s?: string) => void = (s?: string) => {
console.log(s || '无值');
}
const f2 = (s1: string, s2: string = '默认值') => {
console.log(s2);
}
f1();
f2('aaa');
//局部类型文件、全局类型文件、命名空间
const stu: Student = {
name: "zhangsan",
age: 13,
hobby: undefined
} as Student
console.log(stu);
const d: Info.dog = {
name: "dog",
age: 14
} as Info.dog
console.log(d);
return (
<View style={styles.root}>
<Button
title="按钮"
onPress={onButtonPress}
>
</Button>
</View>
)
}
const styles = StyleSheet.create({
root: {
width: '100%',
height: '100%',
backgroundColor: '#f0f0f0'
}
})
ts文件夹下,新建@types文件夹,再新建index.d.ts,代码如下:
//局部类型文件,如果要全局类型文件,直接在最外层新建typing.d.ts
type Student = {
name: string,
age: number,
hobby?: string[]
}
declare namespace Info {
type dog = {
name: string,
age: number
}
}
网友评论