3

使用传统的函数语法,可以内联创建命名函数。

var fn = function myName(arg) {
    // whatever
};
// fn.name === "myName"

可以使用 lambda 语法在 typescript 中指定名称吗?

var fn = (arg) => {
    // whatever
};
// fn.name not set
4

2 回答 2

2

看起来你不能这样做,因为规范没有涵盖它,只有在“延迟”下的末尾它声明“命名箭头函数表达式的可选前导标识符”。

于 2014-12-29T19:44:41.107 回答
1

是的,但这有点棘手。

箭头函数从分配它的变量中获取名称。称为从该变量推断出的名称(在您的情况下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");

于 2021-04-23T07:55:10.690 回答