乐趣区

关于typescript:typescript笔记2

typescript 类型

1、函数多参

type addType = (x: number, y: number) => number
let addxy: addType = (ar1, ar2) => ar1 + ar2;

// 可选参数
type addType2 = (x: number, y: number, z?: number) => number
let addxyz: addType2;
addxyz = (x, y) => x + y;
addxyz = (x, y, z) => x + y + z;  // 这种函数会笼罩后面的

let addx1 = (x: number, y = 3) => {return x + y}
addx1(1);
addx1(2, 2);

// 多个参数
let addx2 = (ar1: number, ...args: number[]) => {}

2、函数重载

function reverse(x: number): number;
function reverse(x: string): string;

// 函数实体
function reverse(x: any) {if (typeof x === 'number') {return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {return x.split('').reverse().join('');
    }
}

reverse(1)
reverse('abc')

3、泛型

  • 问题:
const getArray = (value: any, times: number = 5) => {return new Array(times).fill(value)
}
console.log(getArray(5, 4).map(item => item.length))  // 因为 value 是 any, 然而 lenth 只有 value 是字符串的时候才可用, 然而这里没有报错 
  • 计划:
const getArray2 = <T>(value: T, times: number = 5): T[] => {return new Array(times).fill(value)
}
console.log(getArray2('abc', 5).map(item => item.length)) // ok
console.log(getArray2(12345, 5).map(item => item.length)) // error
// 如果须要 value 是 length 属性的
interface IwithLength {length: number}

const getArray22 = <T extends IwithLength>(value: T, times: number = 5): T[] => {return new Array(times).fill(value)
}
getArray22(12345, 5);// error
getArray22('12345', 5);// ok
// 多个泛型
const getArray3 = <T, U>(x: T, y: U, times = 5): Array<[T, U]> => {return new Array(times).fill([x, y])
}
console.log(getArray3(1, 2))
console.log(getArray3('a', 2))
// 与 keyof 联合
const getProps = <T, K extends keyof T>(obj: T, prop: K) => {return obj[prop]
}
var myObj = {
    name: 'xing',
    age: 32
}
console.log(getProps(myObj, 'name'))
console.log(getProps(myObj, 'year')) // error
  • 泛型类型
type F1 = <T, U>(x: T, y: U, times: number) => Array<[T, U]>

let getArray4: <T, U>(x: T, y: U, times: number) => Array<[T, U]>

interface F2 {<T, U>(x: T, y: U, times: number): Array<[T, U]>
}

interface F3<T, U> {(x: T, y: U, times: number): Array<[T, U]>
    array: [T, U]
}

function xxx<T, U>(x: T, y: U, times: number): Array<[T, U]> {return [[x, y]]
}
退出移动版