TypeScript学习(实战react)

TypeScript学习(实战react)

声明合并

interface A {
    x: number;
    foo (bar: number) number; // 4
}

interface A {
    y: number;
    // 实现函数重载
    // 重载顺序原则: 同接口中按顺序排列 后面的接口A 排在前面的接口A之前
    foo (bar: string): string;  // 2
    foo (bar: number[]): number[]; // 3
    foo (bar: "a") number; // 1  函数自变量为字符串
}

let a: A = {
    x: 1,
    y: 1,
    foo (bar: any) {
        return bar
    }
}
// 类 函数 命名空间合并
function Lib() {}
namespace Lib {
    export let version = '1.0'
}
    
class C {}
    
namespace C {
    export let state = 1
}
    
namespace Color {
    export function mix() {}
}
enum Color {
    Red,
    Yellow,
    Bule
}

如何编写声明文件(找一个知名类库的编写参)

一些非Ts书写的类库需要为这个类库编写一个声明文件(大多数的类库会自带声明文件)

npm i jquery
npm i @type/jquery -D  // 安装声明文件
import $ from 'jquery'

$('.app').css('color', 'red')
  • 在libs 文件夹内建立一个xxx-lib.d.ts文件
const version = '1.0.0'

function dosome() {
    console.log(dosome)
}

function modulelib(options) {
    console.log(options)
}

moduleLib.version = version;
moduleLib.dosome = dosome;

module.export = moduleLib;
declare function moduleLib(options: Options): void

interface Options {
    [key: string]: any
}

declare namespace moduleLib {
    const version: string
    function dosome(): void
}

export = moduleLib
import moduleLib form './modulelib'
module.dosome()

配置tsconfig.json()

文件选项()

{
  "compilerOptions": {

    /* 基本选项 */
    "target": "es5",                       // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs",                  // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [],                             // 指定要包含在编译中的库文件
    "allowJs": true,                       // 允许编译 javascript 文件
    "checkJs": true,                       // 报告 javascript 文件中的错误
    "jsx": "preserve",                     // 指定 jsx 代码的生成: 'preserve', 'react-native', or 'react'
    "declaration": true,                   // 生成相应的 '.d.ts' 文件
    "sourceMap": true,                     // 生成相应的 '.map' 文件
    "outFile": "./",                       // 将输出文件合并为一个文件
    "outDir": "./",                        // 指定输出目录
    "rootDir": "./",                       // 用来控制输出目录结构 --outDir.
    "removeComments": true,                // 删除编译后的所有的注释
    "noEmit": true,                        // 不生成输出文件
    "importHelpers": true,                 // 从 tslib 导入辅助工具函数
    "isolatedModules": true,               // 将每个文件作为单独的模块 (与 'ts.transpileModule' 类似).

    /* 严格的类型检查选项 */
    "strict": true,                        // 启用所有严格类型检查选项
    "noImplicitAny": true,                 // 在表达式和声明上有隐含的 any类型时报错
    "strictNullChecks": true,              // 启用严格的 null 检查
    "noImplicitThis": true,                // 当 this 表达式值为 any 类型的时候,生成一个错误
    "alwaysStrict": true,                  // 以严格模式检查每个模块,并在每个文件里加入 'use strict'

    /* 额外的检查 */
    "noUnusedLocals": true,                // 有未使用的变量时,抛出错误
    "noUnusedParameters": true,            // 有未使用的参数时,抛出错误
    "noImplicitReturns": true,             // 并不是所有函数里的代码都有返回值时,抛出错误
    "noFallthroughCasesInSwitch": true,    // 报告 switch 语句的 fallthrough 错误。(即,不允许 switch 的 case 语句贯穿)

    /* 模块解析选项 */
    "moduleResolution": "node",            // 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "baseUrl": "./",                       // 用于解析非相对模块名称的基目录
    "paths": {},                           // 模块名到基于 baseUrl 的路径映射的列表
    "rootDirs": [],                        // 根文件夹列表,其组合内容表示项目运行时的结构内容
    "typeRoots": [],                       // 包含类型声明的文件列表
    "types": [],                           // 需要包含的类型声明文件名列表
    "allowSyntheticDefaultImports": true,  // 允许从没有设置默认导出的模块中默认导入。

    /* Source Map Options */
    "sourceRoot": "./",                    // 指定调试器应该找到 TypeScript 文件而不是源文件的位置
    "mapRoot": "./",                       // 指定调试器应该找到映射文件而不是生成文件的位置
    "inlineSourceMap": true,               // 生成单个 soucemaps 文件,而不是将 sourcemaps 生成不同的文件
    "inlineSources": true,                 // 将代码与 sourcemaps 生成到一个文件中,要求同时设置了 --inlineSourceMap 或 --sourceMap 属性

    /* 其他选项 */
    "experimentalDecorators": true,        // 启用装饰器
    "emitDecoratorMetadata": true          // 为装饰器提供元数据的支持
  }
}

Ts实战

  • 函数组件
import React from 'react'

interface Greeting {
    name: string
}

const Hello = (props: Greeting) => <h1>Hello {props.name}</h1>

export default Hello

类组件

import React, { Component } from 'react'
import { Button } from 'antd'

interface Greeting {
    name: string;
    firstName: string;
}

interface State {
    count: number
}

class HelloClass extends Component<Greeting, State> {
    state: State = {
        count: 0
    }
    static defaultProps = {
        firstName: '',
    }
    
    render() {
        return <>
        	<p>{this.state.count}</p>
            <Button onClick={() => {this.setState({ count: this.state.count + 1 })}}>Hello {this.props.name}</Button>
        </>
    }
}

export default HelloClass

hoc

import React, { Component } from 'react'
import HelloClass from './HelloClass'

interface Loading {
    loading: boolean;
}
function HelloHoc<P>(c: React.ComponentType<P>) {
    return class extends Component<P & Loading> {
        render() {
            const { loading, ...props } = this.props
            return loading ? <p>loading</p> : <c {...props as P}></c>
        }
    }
}

export default HelloHoc

hooks

import React, { useState, useEffect } from 'react'
import { Button } from 'antd'

interface Greeting {
    name: string;
    firstName: string;
}

const HelloHooks = (props: Greeting) => {
    const [count, setCount] = useState(0);
    const [text, setText] = useState<string | null>(null) // 联合类型
    useEffect(() => {
        if(count > 6) {
            setText("stop")
        }
    }, [count])
     return <>
        	<p>{count}{text}</p>
            <Button onClick={() => {setCount({ count: this.state.count + 1 })}}>Hello {props.name}</Button>
        </>
}

HelloHooks.defaultProps = {
    firstName: "",
    name: "maxloong"
}

export default HelloHooks

事件处理

// interfce 文件夹下面的 employee.ts文件 声明请求接口的类型
export interface EmployeeRequest {
    name:string;
    id: number | undefined;
}

interface EmployeeInfo {
    id: number;
    key: number;
    name: string;
    level: string;
}

export type EmployeeResponse = EmployeeInfo[] | undefined
handleChange = (e: React.FormEvent<HtmlInputElement>) => {
    this.setState({
        name: e.target.value
    })
} 

handleSubmit = () => {
    this.queryEmployee(this.state)
}

componentDidMount() {
    this.queryEmployee(this.state)
}

queryEmployee(param: EmployeeRequest) {
   	get(URL, params).then(res => {
        console.log(res.data)
    })
}
// axios
import originAxios from 'axios'
import { message } from 'antd'

const axios = originAxios.create({
    timeout: 20000
})

axios.interceptors.response.use(
	function(response) {
        if (response.data && response.data.flag === 1) {
            let errorMsg = response.data.msg;
            msessage.error(errorMsg);
            return Promise.reject(errorMsg);
        }
        return response.data;
    },
    function(error) {
        return Promise.reject(error)
    }
);

export function get(url: string, data: any) {
    return axios.get(url, {
        params: data
    })
}

export function post(url: string, data: any) {
    return axios({
        method: "post",
        url.
        data
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaxLoongLvs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值