[英]Typescript function overloading with object
I have a function that accepts an object as the only parameter. 我有一个接受对象作为唯一参数的函数。 For example:
例如:
interface MyMap<T> {
[id: string]: T;
}
type Options = {
asObject: boolean,
other?: Function
};
function get(options: Options): any[];
function get(options: Options): MyMap<any>;
function get(options: Options): any[] | MyMap<any>;
function get(options: Options = {asObject: false, other: () => {}}): any[] | MyMap<any> {
if (options.asObject) return {} as MyMap<any>;
return [];
}
const result = get({asObject: true});
When the asObject value is true, I want to infer the type to MyMap. 当asObject值为true时,我想将类型推断为MyMap。 I know how to do it with simple boolean value, but how can I accomplish this with an object?
我知道如何使用简单的布尔值来执行此操作,但是如何使用对象来完成此操作?
function get(options: {asObject: true}): MyMap<any>;
function get(options: {asObjectb false}): any[];
function get(): any[];
function get(options: Options = {asObject: false, other: () => {}}): any[] | MyMap<any> {
// ...
}
Should be all that you need. 应该是您所需要的。 This will overload the function for the literal types
true
and false
of the property asObject
. 这将重载属性
asObject
的文字类型true
和false
的asObject
。
Note that when overloads are declared, the implementation itself does not contribute a signature to the overload set. 请注意,在声明重载时,实现本身不会为重载集提供签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.