typescript取下级值


typescript取下级值

// type1 返回函数返回值的下级
// 定义接口类型
interface resType {
   data?: Object
}
  
export const baseApi = ({ method = 'get', headers = {}, params = {}, url = '', path = '' }) => {
  let promise = new Promise((reslove, reject) => {
    let option = {
      url: path,
      method,
      timeout: 120000,
      params,
      headers
    }
    let options = (option as optionsType)

    if (method === 'get') {
      options.params = params
    } else if (['post', 'put'].includes(method)) {
      options.data = params
    }

    if ((<any>headers)['content-type']) {
      (<any>headers)['content-type'] = 'application/x-www-form-urlencoded'
    }

    (<any>options).headers = headers || {}
      
    axios(options)
      .then((res: resType) => {
        // 若不定义接口类型(注释data),此处 会报 :类型“resType”上不存在属性“data”。
        // 导致程序运行不下去
        reslove(res.data)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
  return promise
}
// type 2 取得变量的值

interface resLogin {
  code?: number,
  data?: object
}
  
 const Login: React.FC<{}> = (props) => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  
  let history = useHistory();

  const onFinish = async (values: any) => {
    console.log('Success:', values);
    const { username, password } = values
    let result = await userLogin({ params: { username, password } }) as resLogin
    
    // 若不定义 resLogin 接口 ,此处会报错
    if(result.code === 200){
      history.push("/layout");
    }
  };
     .....
     
// type 3 定义将要赋值的对象

import React from 'react'
import axios from 'axios'

interface resType {
  data?: Object
}

interface optionsType {
  url?: string,
  method?: string
  timeout?: number,
  params: object,
  data?: object,
  headers?: object
}

export const baseApi = ({ method = 'get', headers = {}, params = {}, url = '', path = '' }) => {
  let promise = new Promise((reslove, reject) => {
    let option = {
      url: path,
      method,
      timeout: 120000
    }
    // 类型断言
    let options = option as optionsType

    if (method === 'get') {
      options.params = params
    } else if (['post', 'put'].includes(method)) {
      options.data = params
    }
    
    // 函数参数传入, 尚且不知如何定义类型 
    if ((<any>headers)['content-type']) {
      (<any>headers)['content-type'] = 'application/x-www-form-urlencoded'
    }

    options.headers = headers || {}

    axios(options)
      .then((res: resType) => {
        reslove(res.data)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
  return promise
}

// 补充: promise 存放的将来发生的事情, 在调用此封装函数时 , 
// 可使用 async  await 获得promise 成功 (reslove) 失败 (reject) 状态的值 。

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录