簡體   English   中英

類型“字符串”不可分配給類型“T”。 使用 typescript

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

我有下一個場景:

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

問題:為什么會出現這個問題,如何解決?

您必須指定“輸入”類型。

as: HTMLEl = "input" as T,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM