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
的类型,然后将其传递给 ComponentProps
类型。这样就能够将 props 的类型自动推断为 TestProps
。
例如:
import React, { FC, ComponentProps } from 'react'
interface TestProps {
test: string;
}
const Test: FC<TestProps> = () => {
return null;
}
const config1 = {
component: Test,
props: {} // 此时会自动推断为 TestProps 类型
}
function defineConfig<T>(config: { component: T, props: ComponentProps<T> }) {
return config;
}
const config2 = defineConfig<TestProps>({
component: Test,
props: {
test: 'test'
}
})
上述代码中,defineConfig
函数的泛型参数 T
被用于推断 component
的类型,然后通过 ComponentProps<T>
推断出 props
的类型。
如果未来的 TypeScript 版本支持更高级的类型系统或改进推断算法,可能会有更直接的方式来实现根据组件自动推断 props 的类型,但具体形式还需要根据 TypeScript 的发展来确定。