ts 泛型

2022-05-17  本文已影响0人  暴躁程序员

函数泛型

function login<U, P>(username: U, password?: P): object {
  return {
    username: username,
    password: password,
  };
}
console.log(login<string, number>("字符串", 123456789));
console.log(login(100)); // 类型推断会默认将第一个参数的数据类型作为泛型指定的类型,这样写也没问题

接口,类泛型

interface Login<U, P> {
  username: U;
  password: P;
  login(username: U, password: P): object;
}

class LoginClass<U, P> implements Login<U, P> {
  username: U;
  password: P;
  login(): object {
    return {
      username: this.username,
      password: this.password,
    };
  }

  constructor(username: U, password) {
    this.username = username;
    this.password = password;
  }
}

// const login = new LoginClass<string, number>("xiaoming", 123456789); // 正确姿势
const login = new LoginClass("xiaoming", 123456789); 
console.log(login.login());
上一篇下一篇

猜你喜欢

热点阅读