是否可以构造一个 TypeScript 类型,它只会选择那些 typeof X 的属性?
interface IA {
a: string;
b: number;
}
interface IB extends IA {
c: number | string;
}
type IAStrings = PickByType<IA, string>;
// IAStrings = { a: string; }
type IBStrings = PickByType<IB, string>;
// IBStrings = { a: string; }
type IBStringsAndNumbers = PickByType<IB, string | number>;
// IBStringsAndNumbers = { a: string; b: number; c: number | string; }
Run Code Online (Sandbox Code Playgroud) 这是一些条件类型的代码
class A {
public a: number;
}
class B {
public b: number;
}
type DataType = "a" | "b";
type TData<T extends DataType> =
T extends "a" ? A :
T extends "b" ? B :
never;
Run Code Online (Sandbox Code Playgroud)
现在我想使用条件类型作为从函数参数到其返回类型的链接.我尝试以不同的方式实现这一点而没有结果:
function GetData<T extends DataType>(dataType: T): TData<T> {
if (dataType == "a")
return new A();
else if (dataType == "b")
return new B();
}
Run Code Online (Sandbox Code Playgroud)
什么是正确的语法?TypeScript 2.8有可能吗?
更新
在 TypeScript 中,您可以在派生类中拥有协变方法参数。
这看起来像是公然违反LSP。
这部分语言设计的意图是什么,是故意的还是设计限制?
interface A {
a: number;
}
interface B extends A {
b: number;
}
class Base {
public foo(arg0: A): B {
return { a: 0, b: 42 };
}
}
class Derived extends Base {
public foo(arg0: B): B { // covariant parameter is allowed, not OK
return { a: +arg0.a.toPrecision(2), b: +arg0.b.toPrecision(2) }; // runtime error, b is undefined, although should have been required
}
}
let b: Base = new Derived(); // …Run Code Online (Sandbox Code Playgroud)