首页 > 解决方案 > ts 一个同时是函数和属性的类型

问题描述

我正在阅读 ts 手册,我发现一些非常令人困惑的东西,我不知道如何使用它。基本上是一个参数,它同时是一个函数和一个属性。

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

// but how can I use it?
// case 1 fail

doSomething({ description: 'xxx'})

/* Argument of type '{ description: string; }' is not assignable to parameter of type 'DescribableFunction'.
  Type '{ description: string; }' provides no match for the signature '(someArg: number): boolean'.(2345)
*/


//case 2 fail

doSomething((x) => x > 0})

/*
Argument of type '(x: number) => boolean' is not assignable to parameter of type 'DescribableFunction'.
  Property 'description' is missing in type '(x: number) => boolean' but required in type 'DescribableFunction'.(2345)
input.tsx(2, 3): 'description' is declared here.
*/

文档 https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures

example https://www.typescriptlang.org/play?#code/C4TwDgpgBAIhDOBjATgSwEYEN0BsIDEBXAO0WFQHtioBeKAbwCgooATBFVMcqgLinjA0xAOYBuZlAAU8CgFsIAQWQj+xQnPQRkASn7oKFPJmISAvhIBmJMpWqsKAZXkRgAC1Sipl4vzhI0LFwCGx5iHQZJRCpZPAA6HAoRb2I49gCuMKgAaigAIihkV0JkYghWfJyoHykANh0dc0ZGB2cFd09k+jYONG47fgByAA9RwbMdFqcXDq8pYYiaAD4oYagVgAYJoA

标签: typescripttypescript-typings

解决方案


这段代码

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};

意味着有一些(someArg: number): boolean具有静态属性的功能description

就像任何函数都具有静态属性name或静态方法call一样applybind...

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};

function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

const fn: DescribableFunction = (someArg: number) => true
fn.description = 'hello';

doSomething(fn) // ok


推荐阅读