【问题标题】:Is it possible to define custom function types in Typescript是否可以在 Typescript 中定义自定义函数类型
【发布时间】:2020-08-24 19:15:20
【问题描述】:
const obj: Person = { first: 'John', last: 'Thomas'};
interface Person {
first: string;
last: string;
}

要指定一个对象有 first 和 last 属性,我们将其指定为 Person 类型,是否有类似的功能可用于 Typescript 中的函数例如。

const Fun1:(p:Person)=>void = (p) => {
    console.log('first function',JSON.stringify(p))
}

const Fun2:(p:Person)=>void = (p) => {
    console.log('second function',JSON.stringify(p))
}

console.log(Fun1(obj))
console.log(Fun2(obj))

Fun1 和 Fun2 是同一类型的函数,所以我们可以像这样在 TypeScript 中定义一些类型

type Function1 = (p:Person)=> void

const Fun1:Function1 = (p) => {
    console.log('first function',JSON.stringify(p))
}

const Fun2:Function1 = (p) => {
    console.log('second function',JSON.stringify(p))
}

console.log(Fun1(obj))
console.log(Fun2(obj))

【问题讨论】:

  • 上面的代码有什么问题?什么没用?它看起来在语法上是正确的? type SomeFunction = (arg1: string, arg2: number, ...args: any[]) => void;
  • 我的问题是,是否可以编写块 3 作为块 2 的优化
  • 我的回答是这样的,在本地测试时,我可以使用您的块 3 代码,需要方法调用上的正确签名,但它不需要函数声明上的正确签名。示例:这是完全有效的:const fun1: Function1 = () => {} 这在某种程度上是有道理的,因为这将允许重载函数。即使没有指定类型,我在尝试使用不同类型时仍然会收到类型提示/类型错误,所以是的,我觉得(如果我理解正确的话),你可以使用块 3 代替块 2,在我看来,块 3 更多可读。
  • 谢谢@Isolated,是的,我也确认它有效!我只是出于好奇才写的
  • @AkshayVijayJain 总是值得检查是否有更好的方法,或者只是对你的方法进行验证,所以没有问题,我个人更喜欢第 3 块,当然这都是意见,因为它是无论如何都编译成 JavaScript。

标签: typescript interface casting


【解决方案1】:

是的,可以通过以下两种方式在 Typescript 中定义自定义函数类型

第一种方式:

type SomeFunction = (arg1: string, arg2: number) => void;

第二种方式:

interface SomeFunction {
(arg1:string, arg2:number):void
}


然后我们可以在定义函数的同时使用这个自定义函数类型如下

const newFunction:SomeFunction = (arg1,arg2) => { console.log(arg1,arg2) }

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多