使用 TypeScript,您可以显示变量实现具有以下接口:
type Component<P = { children: string | number }> = (
props: P
) => string | number;
const Children1: Component = props => props.children;
这导致:
const Children1 = props => props.children;
是否有可能用常规功能实现类似的事情?其输出如下所示:
// Where does the type information go?
function Children2(props) {
return props.children;
}
你可以在 TypeScript Playground 上玩这个例子
(至于为什么,常规功能很有用,因为您可以提升它们(
您不能按照您想要的方式注释函数。 GitHub 中有一个建议支持这一点,标记为"需要调查"。 如果你想看到这种情况发生,你可能想去那个问题,如果它比已经存在的更引人注目,你可能需要去找它一个👍和/或描述你的用例。
我能最接近您的意图的是使用条件类型,如预定义的ReturnType<T>
和相关Parameters<T>
类型:
function Children2(...[props]: Parameters<Component>): ReturnType<Component> {
return props.children;
}
这应该表现得类似,而且不应该扩展得太可怕。 不幸的是,它很可能在泛型函数中行为不正确。 如果您需要此功能并解决吊装问题,我会坚持使用const
变量。
希望有帮助;祝你好运!
链接到代码
键入函数是这样的:
function myFunction(a: ParamType): ReturnType {
// your function here
}
然后从参数和返回类型推断函数的接口。
函数的返回类型通常可以通过打字稿解释器推断出来。如果要声明其他类需要实现的接口,则函数类型最有用。