【问题标题】:TypeScript Call Signature ExampleTypeScript 调用签名示例
【发布时间】:2022-11-15 22:40:28
【问题描述】:

所以我正在阅读this 文档,我真的很困惑这在 JavaScript 中是如何实现的。

type DescribableFunction = {
   description: string;
   (a: any): boolean;
};
function doSomething(fn: DescribableFunction) {
   console.log(fn.description + " returned " + fn(6));
};

doSomething((()=>false)); // Argument of type '() => false' is not assignable to parameter of type 'DescribableFunction'. Property 'description' is missing in type '() => false' but required in type 'DescribableFunction'.

doSomething({description: 'test'}); // fn is not a function.

正如您在上面看到的,参数fn 怎么可能同时是对象和函数..?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    函数是一种特殊类型的对象——它们本质上是可调用对象.

    const fn = () => {};
    console.log(fn instanceof Object);

    函数的原型链是:

    fn <- Function.prototype <- Object.prototype
    

    对象可以有任意键值对。

    'use strict';
    const fn = () => {};
    fn.prop = 'val';
    console.log('prop is:', fn.prop);

    因此,对于您问题中的函数如何工作的示例,您可以执行以下操作:

    const fn = Object.assign(
      () => false,
      { description: 'test' }
    );
    
    doSomething(fn);
    

    现在fn 既可以调用,也有一个description 属性,它是一个字符串。

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 2015-03-13
      • 2018-09-14
      • 2017-09-13
      • 1970-01-01
      • 2019-04-20
      • 2021-10-27
      • 2017-09-01
      相关资源
      最近更新 更多