TS获取函数组件类型
TS获取函数组件类型
- 获取函数参数的类型
- 获取函数返回值的类型
- 获取组件的 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>;
|
✅ 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>;
|
✅ 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>;
|
对于类组件:
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>;
|
✅ 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'] |
如果你有具体的函数或组件代码,我可以帮你直接推导出类型。