函数泛型
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());
网友评论