简体   繁体   中英

Type 'string' is not assignable to type 'T'. using typescript

I have the next scenario:

export type TagType = 'input' | 'textarea';

interface ContainerProps<T extends TagType> {
  title: string;
  as: T;
  className?: string;
}

My component looks like this:

const Container = <T extends TagType>({
  title,
  as: HTMLEl = 'input',
  ...rest
}: ContainerProps<T> &
  (
    | React.TextareaHTMLAttributes<HTMLTextAreaElement>
    | React.InputHTMLAttributes<HTMLInputElement>
  )) => { ... }

The issue appears as: HTMLEl = 'input', with the next message:

TS2322: Type '"input"' is not assignable to type 'T'.   '"input"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'ElementType'.

Question: Why this issue appear and how to solve it?

you must specify the "input" type.

as: HTMLEl = "input" as T,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM