ts 泛型

作者: 暴躁程序员 | 来源:发表于2022-05-17 09:05 被阅读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());

相关文章

网友评论

      本文标题:ts 泛型

      本文链接:https://www.haomeiwen.com/subject/zupnurtx.html