Home > Software design >  TypeScript extend parameter type
TypeScript extend parameter type

Time:10-04

I want to call a function from my UI library with a type which extends the original (Suggestion) parameter type with additional properties. According to this link it looks like it should be possible: Type '(suggestion: AppSuggestion) => string' is not assignable to type '<T = {}>(suggestion: Suggestion & T) => string'.
Types of parameters 'suggestion' and 'suggestion' are incompatible.
Property 'enabled' is missing in type 'Suggestion' but required in type 'AppSuggestion'.(2322)

I have also tried using interfaces instead, but without luck.

Type '(suggestion: AppSuggestion) => string' is not assignable to type '(suggestion: T) => string'.
Types of parameters 'suggestion' and 'suggestion' are incompatible.
Type 'T' is not assignable to type 'AppSuggestion'.(2322)

CodePudding user response:

The generic type parameter should be on the interface and the component, not the function. If you have a generic function the implementation ((suggestion: AppSuggestion) => 'hello from app') needs to accept any type argument for the type parameter, which it currently does not.

You need to put the type parameter on the component and the props. This means that the type parameter will be inferred when you create your component:

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'}
        />
    )
}

Playground Link

  • Related