类型推论 联合类型 和 类型断言 Utility type (实用类型)

// Type Inference 类型推论 在没有明确使用类型的时候 推测一个类型
let str = 'str' // str 自动获得一个string类型

// union [ˈjuːniən]  types 联合类型
let numberOrString: number | string 
numberOrString = 123
numberOrString = '123'
// 联合类型 只能访问所有类型属性 共有的属性和方法

// 类型断言 表示比这个编辑器更了解这个类型 并且不该发生错误 使用as关键字
function getLength(x: number | string): number {
    const str =  x as string
    if (str.length) {
        return str.length
    } else {
        const number = x as number
        return number.toString.length
    }
}

// type guard 类型守卫  typeof  智能缩小类型范围
function getLength2(x: number | string): number {
    if (typeof x === 'string') {
        return x.length
    } else {
        return x.toString.length
    }
}
 
// Utility type (实用类型)
export const useHttp = () => {
  const {user} = useAuth()
  // return ([endpoint, config]: [string, Config]) => http(endpoint, {...config, token:user?.token})
  return (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {...config, token:user?.token}) // typeof后把整个http中的类型提取出来
  // return (endpoint: string, config: Config) => http(endpoint, {...config, token:user?.token})
}
// utility type(实用类型) 的用法: 用泛型给它传入一个其他类型, 然后utility type 对这个类型进行某种操作
// Parameters就是给它传入一个函数类型  Parameters读出函数类型中的参数类型 
// JS中的typeof是在runtime中运行的
// return typeof 1 === 'number'
// TS 中的 typeof 是在静态环境中运行的 是用来操作类型的

// 联合类型
// let stringOrNumber: string | number
// stringOrNumber = 7
// stringOrNumber = 'str'

// 类型别名
// type FavoriteNumber = string | number

// let a:FavoriteNumber
// a = 13
// a = 'dsd'

// 类型别名在很多情况下可以和interface互换
// interface Person {
//   name: string
// }
// type Person = { name: string }
// let str: Person = { name: 'HKY' }
// type 可以声明基本类型别名,联合类型,元组等类型 而 interface不可以


// type Person = {
//   name: string,
//   age: number
// }

// const xiaoming: Partial<Person> = { name: 'xiaoming'} // 可选 
// const shenmiren: Omit<Person, 'name' | 'age'> = {} // 删除指定属性
posted @ 2021-04-06 17:41  贺可英  阅读(108)  评论(0)    收藏  举报