首页 > 解决方案 > 如何在打字稿中定义函数调用签名的实现和构造签名

问题描述

打字稿文档讨论了函数call signaturesconstruct signatures并描述了如何声明类型和使用它。https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures

调用签名(没有实现 type 的函数DescribableFunction

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



构造签名(没有实现 type 的函数SomeConstructor

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}



但它从未显示如何定义这些函数的实际实现。我搜索了很多天,但似乎找不到任何东西。一个简单的例子,说明如何使用它以及何时使用它,对于理解这些概念非常有帮助。
我试图这样做,call signatures但显然它的抛出错误

type DescribableFunction = {
  description: string;
  (str: string): string;
}

const df: DescribableFunction = {
  description: 'df function description',
  (str: string): {
    return str;
  }
}

console.log(df.description, df('hello world'));

ts游乐场链接

标签: typescript

解决方案


没有用于声明具有额外属性的函数的“文字”语法。
但是函数是普通对象,可以给它们添加属性:

const df: DescribableFunction = (str: string) => {
  return str;
}
df.description = "df function description"

通常,Typescript 会抱怨description在 的初始声明中缺少属性df,但看起来它对函数做了一个例外,允许稍后添加它们。

至于构造函数签名,它们很好地映射到类语法。举个例子:

type CacheableConstructor = {
  new(s: string): { x: number };
  cached: boolean
};

它可以这样实现:

class SomeCC {
  static cached = false
  x: number
  constructor(s: string) {}
}

// check that if matches the constructor signaure
const cc: CacheableConstructor = SomeCC

推荐阅读