如何键入附加为属性的附加功能的函数对象?

时间:2016-09-30 20:20:03

标签: typescript

在TypeScript中,我想创建一个模块来导出一个添加了附加功能的函数,如下所示:

export default function log(msg: string) {
    console.log(msg);
}

//Property 'warn' does not exist on type '(msg: string) => void'.
log.warn = function(msg: string) {
    console.warn(msg);
};

使用方法如下:

log('test');
log.warn('test');

如何告诉TypeScript我的函数对象上有其他属性,以便它不会抛出Property 'warn' does not exist on type '(msg: string) => void'.

2 个答案:

答案 0 :(得分:1)

你会这样写:

function log(msg: string) {

}
namespace log {
  export function warn(omen: string) { }
}

export default log;

答案 1 :(得分:1)

像这样:

const log: { (msg: string): void; warn?: Function; } = function (msg: string) {
  console.log(msg);
}

log.warn = function (msg: string) { console.warn(msg); };

export default log;

换句话说,具有属性的函数类型可以声明为

type FuncWithProp = {
  (FUNC_PARAMS): FUNC_RETURN_TYPE;
  YOUR_PROP_HERE: SOME_TYPE;
};

如果你想更紧密地输入附加函数来获取字符串并输出它们,并允许其他函数,那么

type Logger = {
  (msg: string): void;
  warn?: Logger;
  error?: Logger;
};

const log: Logger = function...
log.warn = function...
export default log;