英文:
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() // 返回 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() // 返回 Bar<never>
Bar.make({}) // 返回 Bar<Foo>
英文:
How to condition the generic of return type if value is not present?
type Foo = {};
class Bar<P extends Foo> {
static make<P extends Foo>(a?: P): Bar<P> {
return new Bar();
}
}
Bar.make() // return Bar<Foo>
But I need to do something like:
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>
答案1
得分: 1
You need to apply a default type 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
Here is a TypeScript Playground link to showcase the different outcomes.
英文:
You need to apply a default type 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
Here a TypeScript Playground link to showcase the different outcomes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论