2

我的功能如下所示:

function calc(a, b){
  return a + b
}

我可以得到它的名字

calc.name

并获得名称 'calc' 。

我也有创建功能

interface ICreateResult {
  [???]: string;
  'key': string;
}

function create(func): ICreateResult{
  return {
    [func.name]: 'some value',
    'key': 'some value'
  }
}

我怎样才能使typescript验证

const obj = create(calc);
obj.calc // intellisense by typescript
obj.abc() // error
4

2 回答 2

0

我认为在当前版本的 TypeScript 中是不可能的。

参见示例:

const x = (a: number) => a

type FnName = (typeof x)['name'] // string

FnName被推断为 astring而不是文字字符串类型x

于 2021-06-20T08:39:53.450 回答
0

据我了解,您想将函数作为参数传递给创建。让我们尝试对您的代码进行一些更改并转换为:

function calc(a: number, b: number) {
  return a + b;
}

function abc() {

}

type strictType = {
  funcSyntax: (a: number, b: number) => number
}

interface ICreateResult {
  funcCall: (a: number, b: number) => number;
  funcName: string;
  key: string;
}

function create(arg: strictType): ICreateResult {
  return {
    funcCall: arg.funcSyntax,
    funcName: arg.funcSyntax.name,
    key: 'some value',
  }
}
const crt = create({ funcSyntax: calc });
console.log(crt.funcCall.call(null, 4, 5));//9
console.log(crt.funcName);//calc

const crt2 = create({ funcSyntax: abc })//error
于 2021-06-20T06:38:16.947 回答