辰風依恛
文章35
标签0
分类11
TS获取函数组件类型

TS获取函数组件类型

TS获取函数组件类型

  1. 获取函数参数的类型
  2. 获取函数返回值的类型
  3. 获取组件的 props 类型

可以使用内置的 工具类型类型推导机制。下面是具体方法:


✅ 1. 获取函数参数的类型:Parameters<T>

1
2
3
4
5
6
function greet(name: string, age: number): string {
return `Hello ${name}, age ${age}`;
}

type Params = Parameters<typeof greet>;
// type Params = [string, number]

✅ 2. 获取函数返回值的类型:ReturnType<T>

1
2
3
4
5
6
function greet(name: string, age: number): string {
return `Hello ${name}, age ${age}`;
}

type Return = ReturnType<typeof greet>;
// type Return = string

✅ 3. 获取组件的 props 类型(React 场景)

对于函数组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';

interface MyProps {
title: string;
count?: number;
}

const MyComponent: React.FC<MyProps> = ({ title, count }) => {
return <div>{title} - {count}</div>;
};

type Props = React.ComponentProps<typeof MyComponent>;
// type Props = MyProps

对于类组件:

1
2
3
4
5
6
7
8
class MyClassComponent extends React.Component<MyProps> {
render() {
return <div>{this.props.title}</div>;
}
}

type Props = React.ComponentProps<typeof MyClassComponent>;
// type Props = MyProps

✅ 4. 获取组件的 props 类型(Vue 场景)

组件内部

1
2
3
4
5
6
7
8
9
<!-- MyButton.vue -->
<script setup lang="ts">
interface Props { // 1. 先写接口
type: 'primary' | 'ghost'
size?: 'sm' | 'lg'
disabled?: boolean
}
const props = defineProps<Props>() // 2. 直接泛型推导
</script>

外部使用

1
2
3
4
import MyButton from './MyButton.vue'

type BtnProps = InstanceType<typeof MyButton>['$props']
// BtnProps ≡ { type: 'primary'|'ghost'; size?: 'sm'|'lg'; disabled?: boolean }

✅ 总结工具类型速查表:

目的 工具类型
获取函数参数类型 Parameters<typeof fn>
获取函数返回值类型 ReturnType<typeof fn>
获取组件 props 类型(React) React.ComponentProps<typeof C>
获取组件 props 类型(Vue) InstanceType<typeof MyButton>['$props']

如果你有具体的函数或组件代码,我可以帮你直接推导出类型。

本文作者:辰風依恛
本文链接:https://766187397.github.io/2025/10/12/TS%E8%8E%B7%E5%8F%96%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E7%B1%BB%E5%9E%8B/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可
×