TypeScript React 从传递的 prop 推断函数参数

huangapple go评论76阅读模式
英文:

TypeScript React infer function argument from passed prop

问题

interface DropdownProps<T> {
	items: {
		value: T;
		title: string;
	}[];
	defaultSelected?: number;
	onSelected: (value: T) => void;
}

export const Dropdown: React.FC<DropdownProps<here>> = (props) => { ... }
英文:

I am trying to replace any type in the code below to something that will allow me to type the value of the onSelected function based on what type was passed as the value in the items array so I dont lose typesafety in the callback.

interface DropdownProps {
	items: {
		value: any;
		title: string;
	}[];
	defaultSelected?: number;
	onSelected: (value: DropdownProps[&quot;items&quot;][number][&quot;value&quot;]) =&gt; void;
}

I tried adding &lt;T&gt; to DropdownProps, but then TS requires to provide something instead of T the component type.

interface DropdownProps&lt;T&gt; {
	items: {
		value: T;
		title: string;
	}[];
	defaultSelected?: number;
	onSelected: (value: DropdownProps&lt;T&gt;[&quot;items&quot;][number][&quot;value&quot;]) =&gt; void;
}

export const Dropdown: React.FC&lt;DropdownProps&lt; here &gt;&gt; = (props) =&gt; { ... }

答案1

得分: 2

onSelected 函数中的 value 的类型将根据 @wonderflame 的评论来设置。以下是相应的代码:

interface DropdownProps<T> {
	items: {
		title: string;
		value: T;
	}[];
	defaultSelected?: number;
	onSelected: (value: DropdownProps<T>["items"][number]["value"]) => void;
}

export const Dropdown = <T>(props: DropdownProps<T>) => { ... }
英文:

Setting the types as per @wonderflame 's comment gives typing on the type of value in the onSelected function

interface DropdownProps&lt;T&gt; {
	items: {
		title: string;
		value: T;
	}[];
	defaultSelected?: number;
	onSelected: (value: DropdownProps&lt;T&gt;[&quot;items&quot;][number][&quot;value&quot;]) =&gt; void;
}

export const Dropdown = &lt;T,&gt;(props: DropdownProps&lt;T&gt;) =&gt; { ... }

huangapple
  • 本文由 发表于 2023年5月23日 01:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定