我有以下设置,我想在其中添加一个额外的属性到现有的函数声明中:
const secret = Symbol('secret');
type ExtendedFunction = {
(input: number): string
[secret]: number;
}
如何创建以类型安全的方式返回此对象的函数?
const createExtendedFunction = (): ExtendedFunction => {
const func: (input: number) => string = (input) => '' + input + ':' + input;
// Error: No index signature (from TSlint only)
func[secret] = 2;
// secret type cannot be verified obviously
return func as unknown as ExtendedFunction;
};
上面的代码有效,但是我没有找到一种将功能和同时分配给对象的方法,我想知道是否还有一种类似TypeScript的方法这样做。
这是我最初认为的样子,但这不起作用:
const createExtendedFunction = (): ExtendedFunction => {
const func: (input: number) => string = (input) => '' + input + ':' + input;
return {
invoke: func,
[secret]: 2
}
};
那么此默认函数invoke属性是否具有call
,invoke
,apply
,default
之类的名称,或者可以通过类型安全的方式设置的名称?