TypeScript 中,如何定义(声明)函数的类型?

2021-02-03 16:53:43 +08:00
 Kasumi20

我知道可以把函数写成变量,就可以声明函数的类型了,比如这里的 Root 组件:

import * as React from 'react';

var Root: React.FC = (props: React.PropsWithChildren<{}>) => {
    return (
        <div>
            {props.children}
        </div>
    )
}

export default () => (
    < >
        <Root>
            <div>Hello</div>
        </Root>
    </>
)

但是太丑了,该怎么写呢?

function Root(props) {
}
2847 次点击
所在节点    程序员
21 条回复
Yadomin
2021-02-03 17:04:25 +08:00
`function Root(props): React.FC {}`
Kasumi20
2021-02-03 17:06:00 +08:00
@Yadomin 大哥,你这是定义返回类型
Yadomin
2021-02-03 17:06:20 +08:00
也可以写成
const Root = (props): React.FC => {}
meepo3927
2021-02-03 17:39:36 +08:00
函数有类型吗
knives
2021-02-03 17:45:39 +08:00
是指 props 的类型定义?可参考: https://juejin.cn/post/6884144754993397767
Kasumi20
2021-02-03 17:46:14 +08:00
@meepo3927 这句话问得很哲学,我喜欢
Justin13
2021-02-03 17:50:06 +08:00
interface 里的 function types 可以做到
BBUG
2021-02-03 17:54:37 +08:00
不行

明确一点,`var Root: React.FC = () => {}` 等号右边的函数声明隐式包含一个类型,左边变量类型相当于是对右边函数类型的一个约束

一般推荐使用常规函数声明组件即可,不需要使用 React.FC
https://github.com/typescript-cheatsheets/react/blob/main/README.md#function-components
iamppz
2021-02-03 18:25:39 +08:00
```
const func: () => void = function () {
...
};
```

是这个意思?
hupo0
2021-02-03 18:49:35 +08:00
``` typescript
interface Root {
(props: React.PropsWithChildren<{}>): React.FC;
}
```
learningman
2021-02-03 21:49:51 +08:00
函数的类型不就是函数,你想说的是返回值?
Reapper
2021-02-04 09:08:26 +08:00
函数就是类型,除非你说返回值类型
yazoox
2021-02-04 09:38:04 +08:00
这个 Root 的类型,就是 React.FC, 返回值是 React.Element<any, any> | null
lanten
2021-02-04 09:43:53 +08:00
其实函数类型的定义就是行参和返回值类型定义,可以直接用 typeof 推断。

```ts
function foo(strArr: string[]): string {
return strArr.join(',')
}

type Foo = typeof foo

```

也可以用 interface 定义函数类型'

```ts
interface F {
(strArr: string[]): string
}

const fn: F = strArr => {
return strArr.join(',')
}
```
1a0ma0
2021-02-04 12:22:23 +08:00
interface 不是可以定义嘛?
siweipancc
2021-02-04 13:43:32 +08:00
……,你先回答我官网文档你看完了吗 :D
Kasumi20
2021-02-04 13:44:32 +08:00
@siweipancc 你先回答我你看完我问题了吗?
ljpCN
2021-02-04 14:29:15 +08:00
14 楼正解。
```typescript
function fn(arg: string): string {
return arg;
}
```
palmers
2021-02-04 16:42:41 +08:00
我知道的可以使用函数声明( Function Declaration )和函数表达式( Function Expression )
具体可以参考这个: https://www.typescriptlang.org/docs/handbook/interfaces.html#function-types
coffeedeveloper
2021-02-04 20:01:27 +08:00
楼上认为能申明的都是没了解实际问题的,这个问题我也困扰过。目前确实是无解的。

比如我想申明一个函数的类型申明,有 x 、y 两个 number 参数,返回一个 number 。可以用 interface

```typescript
interface NumFn {
(x: number, b: number): number
}
```

随后希望 `function Foo` 和`function Bar`都能够基于 NumFn 这个 interface 约定来实现的话,目前确实是没法弄的,只能通过 `const foo = `来勉强达到目的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/750989

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX