[英]TypeScript extend parameter type
我想从我的 UI 库中调用一个 function,其类型扩展了具有附加属性的原始 ( Suggestion
) 参数类型。 根据这个链接,它看起来应该是可能的: https://github.com/Microsoft/TypeScript/issues/2225 (底部评论)
我做错了什么,你做对了吗? 请注意, getSuggestion
function 及其类型位于 UI 库 package 中,我想从我的应用程序 package 中调用它。
代码:
import React from 'react'
type Suggestion = {
name: string
}
interface UIProps {
getSuggestion: <T = {}>(suggestion: Suggestion & T) => string
}
function UIComponent(props: UIProps) {
return null
}
type AppSuggestion = {
name: string
enabled: boolean
}
function AppComponent() {
return (
<UIComponent
getSuggestion={(suggestion: AppSuggestion) => 'hello from app'}
/>
)
}
我也尝试过使用接口,但没有成功。
代码:
import React from 'react'
interface Suggestion {
name: string
}
interface UIProps {
getSuggestion: <T>(suggestion: T) => string
}
function UIComponent(props: UIProps) {
return null
}
interface AppSuggestion extends Suggestion {
name: string
enabled: boolean
}
function AppComponent() {
return (
<UIComponent
getSuggestion={(suggestion: AppSuggestion) => 'hello from app'}
/>
)
}
通用类型参数应该在接口和组件上,而不是 function。如果你有一个通用的 function 实现( (suggestion: AppSuggestion) => 'hello from app'
)需要接受类型参数的任何类型参数,目前没有。
您需要将类型参数放在组件和道具上。 这意味着类型参数将在您创建组件时被推断出来:
interface UIProps<T> {
getSuggestion: (suggestion: T) => string
}
function UIComponent<T>(props: UIProps<T>) {
return null
}
interface AppSuggestion extends Suggestion {
name: string
enabled: boolean
}
function AppComponent() {
return (
<UIComponent
getSuggestion={(suggestion: AppSuggestion) => 'hello from app'}
/>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.