使用传统的函数语法,可以内联地创建命名函数。
var fn = function myName(arg) {
// whatever
};
// fn.name === "myName"
可以使用lambda语法在类型记录中指定名称吗?
var fn = (arg) => {
// whatever
};
// fn.name not set
发布于 2021-04-23 07:55:10
是的,但有点棘手。
箭头函数从分配它的变量中获取名称。它被称为名称是从变量(在您的例子中是fn.name === "fn"
)推断的。存在一些限制,因为该名称不能作为常规标识符使用,因此不能从函数本身中使用它(用于递归或事件解除绑定)。
如果使用以下代码:
const joeThrows = (thing: string):never => {
throw new Error(`Joe took ${thing} and throwed it at you.`);
}
const simonThrows = ({
simonSays: (what: string):never => {
throw new Error(`Simon said ${what} and throwed you out.`);
}
})["simonSays"];
try {
console.log("== joeThrows fat-arrow %s has name '%s' ==", typeof joeThrows, joeThrows.name);
joeThrows("hammer");
} catch(ex) { console.log(ex.stack); }
try {
console.log("=== simonThrows fat-arrow %s has name '%s' ==", typeof simonThrows, simonThrows.name);
simonThrows("I have a name!");
} catch(ex) { console.log(ex.stack); }
然后,您将得到以下输出:
=== joeThrows fat-arrow function has name 'joeThrows' ==
Joe took hammer and throwed it at you.
Error: Joe took hammer and throwed it at you.
at joeThrows (/code-demo/named.js:2:11)
at Object.<anonymous> (/code-demo/named.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
...
=== simonThrows fat-arrow function has name 'simonSays' ==
Error: Simon said I have a name! and throwed you out.
at simonSays (/code-demo/named.js:6:15)
at Object.<anonymous> (/code-demo/named.js:18:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
...
我很少使用对象字段赋值和读取表达式的第二种技术。
当您想要创建更多函数时,可以方便地为不同的设置创建具有相同功能的回调功能,并且希望更精确地可视化异常源,而不是只使用泛型名称。例如,要动态创建非常通用的Redux选择器或FeatherJS挂钩,可以通过函数创建者的参数进行自定义:
// Let's suppose we have the types
type HookContext = Record<string, any>;
type ServiceHook = (context: HookContext) => HookContext;
// Then we can define service hook factory function
export const createServiceHook = (purpose: string): ServiceHook => {
const fn = `serviceHook$${purpose}`;
return ({
[fn]: (context: HookContext): HookContext => {
// Do something here with the context which may throw exception
return context;
}
})[fn];
};
// Later we can create a specific hook function instance that:
// * will have lookoutForSummer.name equal to "serviceHook$summer"
// * will show that name in call-stack in case exception is throw
export const lookoutForSummer = createServiceHook("summer");
https://stackoverflow.com/questions/27694914
复制相似问题