小编And*_*aev的帖子

TypeScript:选择具有定义类型的属性

是否可以构造一个 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)

typescript

7
推荐指数
2
解决办法
3235
查看次数

如何在泛型函数中从参数类型推断返回类型?

这是一些条件类型的代码

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有可能吗?

更新

在github上已经有一个已经打开的问题,它涵盖了我的例子.因此,目前的答案是"不,但未来可能".

typescript conditional-types typescript2.8

6
推荐指数
1
解决办法
310
查看次数

为什么 TypeScript 中的方法参数不是逆变的?

在 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)

typescript

5
推荐指数
1
解决办法
799
查看次数