, , . , .
, , f , . MiniUser FullUser. , :
class MiniUser {
name: string;
constructor(name: string) {
this.name = name;
}
}
class FullUser extends MiniUser {
age: number;
constructor(name: string, age: number) {
super(name);
this.age = age;
}
}
function fetchMiniFn(id: number) {
return new MiniUser("John");
}
function fetchFullFn(id: number) {
return new FullUser("John", 22);
}
function f(fetchUser: (id: number) => MiniUser | FullUser) {
let a = fetchUser(2);
if (a instanceof FullUser) {
console.log("Full User: " + a.name + ", " + a.age);
}
else {
console.log("Mini User: " + a.name);
}
}
f(fetchMiniFn);
f(fetchFullFn);
, , f , , :
function fetch(id: number, representation: 'mini' | 'full') {
if (representation == 'mini') {
return new MiniUser("John");
}
else {
return new FullUser("John", 22);
}
}
type FetchUser = (id: number, representation: 'mini' | 'full') => MiniUser | FullUser;
function f(fetchUser: FetchUser) {
let mini = <MiniUser>fetchUser(2, 'mini');
console.log("Mini User: " + mini.name);
// Call the function with FullUser fetching
let full = <FullUser>fetchUser(2, 'full');
console.log("Full User: " + full.name + ", " + full.age);
}
// Call function:
f(fetch);