typescript在react组件中的使用

278 阅读1分钟

使用方法

本文背景,编辑器vscode, typescript, eslint.

定义基础类型

typescript中文文档

// 布尔值
let isTrue: boolean = false

//数字
let num : number = 4

//字符串
let name : string = 'boble'

//数组
let arr : number[]= [1,2,3,4]
let arrs : Array<string>  //注意<>内部表示数组item的属性,可以设定any或者其他基础类型

//元组
let array :[ string, number ]
array=['age', 25] //true
array=[25,'age'] //error

//void
表示没有任何返回

定义函数

//常规函数
function add(x,y){
    return x+y
}

//ts
function add(x:number,y:munber):number{
    return x+y    
}

在react中使用

//example.tsx

import React , { Component } from 'react'

interface props{
    num: number,
    str: string,
    isTrue:boolean,
    arr: Array<number>,
    array: Array<any>,
    getName: fnc,
}

interface fnc {
  (source: string, subString: string): boolean;
}

export default class Example extends Component<props,any>{
    ....
}