繁体   English   中英

返回类型中的打字稿条件泛型类型

[英]Typescript conditional generic type in return type

如果值不存在,如何调节返回类型的泛型?

type Foo = {};

class Bar<P extends Foo> {
    static make<P extends Foo>(a?: P): Bar<P> {
        return new Bar();
    }
}

Bar.make() // return Bar<Foo>

但我需要做类似的事情:

class Bar<P extends Foo> {
    static make<P extends Foo>(a?: P): Bar<P extends undefined ? never : Foo> {
        return new Bar();
    }
}

Bar.make() // return Bar<never>
Bar.make({}) // return Bar<Foo>

您需要应用默认类型never

type Foo = {test: number}; // Example implementation of foo, used in test cases below

class Bar<P extends Foo> {
  // Allow P to extend from Foo, then assign never as the default
  static make<P extends Foo = never>(a?: P): Bar<P> {
    return new Bar();
  }
}

const t1 = Bar.make(); // Bar<never>
const t2 = Bar.make({ test: 2 }) // Bar<{test: 2}> (subtype of Foo)
const t3: Bar<Foo> = Bar.make({ test: 2 }); // Bar<Foo> (explicit typecasting to Bar<Foo>)
const t4 = Bar.make({ bazz: 0 }); // Type error, { bazz: 0 } is not assignable to Foo

这里有一个TypeScript Playground 链接来展示不同的结果。

暂无
暂无

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

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