TypeScript 如何实现值的泛型,比如根据组件自动推断 props 类型?
据我所知,目前版本的 TS 做不到,必须使用函数包裹一层,知乎上也有其他类似的问题,好奇如果后续能做到的话,会是怎么样的形式?
import React, { FC, ComponentProps } from ‘react’
interface TestProps {
test: string;
}
const Test: FC = () => {
return null;
}
const config1 = {
component: Test,
props: {} // 如何自动推断为 TestProps ?
}
function defineConfig(config: { component: T, props: ComponentProps }) {
return config;
}
const config2 = defineConfig({
component: Test,
props: {
test: ‘test’
}
})
在目前的 TypeScript 版本中,无法直接根据组件自动推断 props 的类型。你提到的使用函数包裹一层的方式是目前较常用的解决方案之一。这种方式可以通过函数的参数类型来推断出组件的 props 类型。
对于你的示例代码,通过使用泛型函数来包裹 defineConfig
函数,可以实现自动推断 props 类型的效果。使用泛型可以让 TypeScript 推断出 props
的类型,