type Hash = {
[k:string]: unknown
length: number
}
// 报错,有in的情况下不能声明其他属性
type Hash = {
[k in string]: unknown
length: number
}
-
?
本质上是 类型 | undefined
-
readonly
类似于const
,只能限定地址不变
- 函数三种声明方式:
function f1(a:number): number{
return a+1
}
type F2 = (a:number) => number
const f2 = (a:number):number => a + 1
---or---
const f2: F2 = (a) => a+1
type F3 = typeof f2
const f3:F3 = function(a){
return a + 1
}
const f3 = function(a: number):number{
return a + 1
}
---or---
type F = () => void
function fn():F{
return
}
const add = (a:number,b:number) => a + b
const ceateAdd = (a:number) => {
return (b:number) => {
return a + b
}
}
// 简化:createAdd(6)(14)
const createAdd = (a:number) => (b:number) => a + b
// 单独声明类型:
type CreateAdd = (x:number) => (y:number) => number
// add6的类型就是一个函数: (b:number)=>number
const add6 = createAdd(6)
add6(14) //20
- 函数重载
overload
:本质是同名的函数
。能不用就不用,直接用不同函数实现替代。但是如果是写功能函数给别人用,就可以使用重载使用者体验良好。
- 参数类型不同:用联合类型,然后js进行类型收窄
// 先声明
function createDate(n:number): Date
function createDate(year:number,month:number,day:number): Date
//再实现
function createDate(a:number,b?:number,c?:number){
if(a !== undefined && b !== undefined c !== undefined){
return new Date(a,b,c)
}else if(a !== undefined && b === undefined && c === undefined){
return new Date(a)
}else{
throw error('只能接受一个或三个参数')
}
}
type Person = {
name: string
}
function fn(this: Person,word: string){
console.log(this.name + '' + word)
}
const p:Peson = {name: 'ricky'}
fn.call(p,'hi')
fn.apply(p,['hi'])
fn.bind(p)('hi') // 柯里化
// 甚至可以
const f1 = fn.bind(p)
const f2 = f1.bind(null,'hi')
f2()
// array就是收集了所有参数的数组
function sum(name: string,...array:number[]){
return array.reduce((previous,current)=>{
return previous + current
},0)
}
console.log(sum('hi',1,2,3,4,5))
function sum(...array: number[]) {
// f(array) 报错:因为函数f是把参数全收集起来才成了number[],意味着每个参数都要是一个number
f(...array)
// or
f.apply(null,array)
}
function f(...arr: number[]) {
console.log(arr);
}
const a = 'a'
type A = typeof a // 'a'
let b = 'b'
type B = typeof b // string
let c = 'c' as const
type C = typeof c // 'c'
const arr = [1,'hi']
type Arr = typeof arr // (number | string)[],因为array是可以改变元素的
const arr = [1,'hi'] as const
type Arr = typeof arr // readonly [1,'hi']
// 函数使用示例
function f(a:number,b:number){
return a + b
}
function sum(...arr:number[]){
// 正确
const x = [1,2] as const
f(...x)
// 报错
f(...arr)
// 报错: x是 number[],但f只接受两个参数
const x = [1,2]
f(...x)
}
type Config = {
url: string
method: 'GET' | 'POST'
data?: unknown
headers?: unknown
}
const ajax = ({url,method,...rest}:Config = {url:'', method: 'GET'}) => {}
---or---
function ajax({url,method,...rest} = {url:'',method:'GET'} as Config){
}