我正在尝试根据条件类型运行替代代码。但是,在 TypeScript 中似乎无法做到这一点。这是我的尝试:
class alt_a {
what(): string {
return "alt_a";
}
}
class alt_b {
what(): string {
return "alt_b";
}
}
// OK
let a: alt_a = new alt_a;
console.log(a.what());
let b: alt_b = new alt_b;
console.log(b.what());
// Doesn't work
type cond<T> = T extends true ? alt_a : alt_b;
let c: cond<true> = new cond<true>;
console.log(c.what());
尝试编译 (tsc --version == "Version 3.3.3333") 时,我得到以下信息:
(30,35): error TS1005: '(' expected.
有没有办法在 TypeScript 中做类似的事情?更好的方法是访问替代类的静态成员,就像 C++ 中的“constexpr”成员一样。
答案 0 :(得分:0)
class alt_a {
what(): string {
return "alt_a";
}
}
class alt_b {
what(): string {
return "alt_b";
}
}
function getConstructor(condition: boolean) {
return condition ? alt_a : alt_b;
}
const constructor = getConstructor(true);
const c = new constructor();
c.what();
答案 1 :(得分:0)
您无法根据打字稿类型在 javascript 代码中做出任何决定。将代码编译为 javascript 时,typescript 类型被完全删除。
cond<T>
只是一种类型。您不能将其用作类构造函数。您还必须定义 javascript 行为并根据 javascript 变量选择正确的类。
type cond<T> = T extends true ? alt_a : alt_b;
const createCond = <T extends boolean>(bool: T): cond<T> => {
// the choice is made based on the variable, not the type
const selected = bool ? alt_a : alt_b;
// have to assert when using a conditional as a return type
return new selected() as cond<T>;
}
const a = createCond(true); // type: alt_a
const b = createCond(false); // type: alt_b