繁体   English   中英

在 TypeScript 中,如何定义提供成员对象返回值的方法类型?

[英]In TypeScript, How to define type of method that provide a value returned from member object?

interface Foo<T> {
    getValue(): T;
}

class Foo1 implements Foo<string> {
    __value: string;

    constructor(value: string) {
        this.__value = value;
    }

    getValue(): string {
        return this.__value;
    }
}

class Foo2 implements Foo<number>  {
    __value: number;

    constructor(value: number) {
        this.__value = value;
    }

    getValue(): number {
        return this.__value;
    }
}

class Bar<T extends Foo1 | Foo2> {
    private __foo: T;

    constructor(foo: T) {
        this.__foo = foo;
    }

    getValueOfFoo() {
        return this.__foo.getValue();
    }
}

const bar1 = new Bar(new Foo1('hello'));
const val1: string = bar1.getValueOfFoo();

const bar2 = new Bar(new Foo2(12345));
const val2: number = bar2.getValueOfFoo();

链接到 TypeScript Playground

我希望 42 和 45 行的返回值是stringnumber但它们不是。

如何定义可以返回正确类型的方法类型取决于通过构造函数提供的对象类型?

它目前没有按预期工作的原因是,您的通用约束被定义为T extends Foo1 | Foo2 T extends Foo1 | Foo2 Typescript 不允许缩小通用联合。 请参阅此问题#13995

问题的要点是来自一位打字稿维护者的评论:

TL; DR 来自设计讨论:“正确”的做法有些明显,但需要对我们如何处理类型参数进行大量修改,具有一致的负面性能影响,而不会对实际用户产生相应的巨大积极影响 -面对行为方面。

如果出现新的模式,使这更频繁地出现问题,我们可以再看看。

解决手头问题的一种快速方法是避免像这样的通用联合,不确定它是否适合您的实际用例:

class Bar<T> {
    private __foo: Foo<T>;

    constructor(foo: Foo<T>) {
        this.__foo = foo;
    }

    getValueOfFoo() {
        return this.__foo.getValue();
    }
}

游乐场链接

我运行了以下代码(您的代码)并看到了正确的结果。

const bar1 = new Bar(new Foo1('hello'));
const val1: string = <string>bar1.getValueOfFoo();
console.log(typeof(val1))

const bar2 = new Bar(new Foo2(12345));
const val2: number = <number>bar2.getValueOfFoo();
console.log(typeof(val2))

控制台输出:

string
number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM