【问题标题】:Different ways of declaring function type in typescript?在打字稿中声明函数类型的不同方法?
【发布时间】:2020-03-17 18:28:13
【问题描述】:

我在 typescript 中发现你可以简单地使用 declare 关键字声明一个函数类型,例如:

declare function test1(name: string): true

const t1 = test1('t') // true

我也可以使用箭头符号来做到这一点:

const test2 = (name: string) => true

const t2 = test2('t') // boolean

它们都可以正常工作,没有任何编译器错误。但似乎最终推断的类型不同,即使我将它们同时指定为true

同时,如果我将返回类型true 更改为一般的原始类型,例如string,第二个示例会给我一个错误:

declare function test1(name: string): string // ok

const test2 = (name: string) => string // error: 'string' only refers to a type, but is being used as a value here.

看起来对于“箭头函数表示法”类型,您必须将返回结果/类型指定为特定结果,例如,如果将其放入最终结果中,泛型也没有意义:

declare function test1<T>(name: T): T // ok

const test2 = <T>(name: T) => T // error: 'T' only refers to a type, but is being used as a value here.

但是,它们都不是“看起来像一个类型”,我的意思是您可以使用const 关键字定义它们(在第二个示例中,通常这是用于声明据我所知是一个变量),然后你可以像普通函数一样调用它们,它会给你返回类型/结果而不实现实际细节:

test1('xxx')
test2('xxx')

所以我的问题是:

  • 它们是真正的类型吗(如类型别名)?他们在打字稿中有实际姓名吗?
  • 这两种符号有什么区别吗?我们如何正确使用它们?

【问题讨论】:

  • 第一个实际上没有创建函数test1 - 执行它会失败。 declare 使编译器假设这将来自 somewhere 而不验证来自哪里。如果没有,那么您在编译时将不会收到错误。
  • 阅读更多问题,您似乎对箭头函数是什么和函数签名是什么感到困惑。当您执行declare function test1(name: string): true 时,您会说 一个与描述匹配的函数(某处):名称是test1,它接受一个字符串参数并且它总是返回真。当您执行箭头函数时,您创建 一个函数,然后 TS 推断它的类型。因此,它构造了一个类似于您在declare 中的条目。签名和函数本身不可互换。

标签: typescript types


【解决方案1】:

当您 declare 某事时,它只是告诉 TypeScript 编译器在运行时将存在该函数/变量/类等,并在编译期间被删除。您指定该事物的类型(或函数的函数签名):

// these are the same
declare function test1(name: string): true
declare const test1: (name: string) => true
test1('') // true

您对test2 所做的是创建了一个将在运行时存在的箭头函数,因为您没有使用declare 关键字并提供了实现:

// these are also the same
function test2(name: string) {
  return true
}
const test2 = (name: string) => true
test2('') // boolean

由于没有明确说明返回类型,TypeScript 推断返回类型为boolean。指定为true

function test3(name: string): true {
  return true
}
const test3 = (name: string): true => true
test3('') // true

【讨论】:

  • 谢谢。我想我只是问了一个非常愚蠢的问题。 const test2 = (name: string) =&gt; true 实际上是实现而不是类型定义。无论如何感谢您的详细解释。
猜你喜欢
  • 1970-01-01
  • 2019-05-05
  • 2019-02-16
  • 2022-01-06
  • 2021-01-12
  • 2018-12-11
相关资源
最近更新 更多