型别'string'无法指派给型别'T',使用typescript

euoag5mw  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(204)

我有下一个场景:

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

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

我的组件如下所示:

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

问题出现as: HTMLEl = 'input',,并显示下一条消息:

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'.

问:为什么会出现这个问题,如何解决?

sr4lhrrt

sr4lhrrt1#

必须指定“input”类型。

as: HTMLEl = "input" as T,

相关问题