Typescript之泛型

2020-06-28 12:19:21 浏览数 (1)

泛型接口的使用

代码语言:javascript复制
function add<T>(arg1: T, arg2: T): T {
  return arg1   arg2;
}

// <T>(arg1:T,arg2:T)=>T

add<number>(1, 2);
add<string>('1', '2')

// let addFunc: <T>(arg1: targ2: T) => T
// let addFunc: { <T>(arg1: T, arg2: T): T }

// interface GenAdder { <T>(arg1: T, arg2: T): T }
interface GenAdder<T> { (arg1: T, arg2: T): T }

let addFunc: GenAdder<string>;
addFunc = add

// addFunc<number>(1, 2)
// addFunc<string>('1', '2')

addFunc('1', '2')

泛型类的使用

代码语言:javascript复制
class Adder<T>{
  add: (arg1: T, arg2: T) => T
}

function add(arg1, arg2) {
  return arg1   arg2;
}

const adder = new Adder<number>();
adder.add = add

const stringAdder = new Adder<string>()
stringAdder.add = add

adder.add(1, 2)
stringAdder.add('1', '2')

泛型约束

代码语言:javascript复制
interface ILength {
  length: number
}

function getLength<T extends ILength>(arg: T): T {
  console.log(arg.length);
  return arg;
}

getLength<string>('liuyi')

function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key]
}


// keyof
const people = { name: "liuyi", age: 32 }
let keys: keyof typeof people

getProperty(people, 'name')
getProperty(people, 'age')

0 人点赞