英文:
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["items"][number]["value"]) => void;
}
I tried adding <T>
to DropdownProps
, but then TS requires to provide something instead of T
the component type.
interface DropdownProps<T> {
items: {
value: T;
title: string;
}[];
defaultSelected?: number;
onSelected: (value: DropdownProps<T>["items"][number]["value"]) => void;
}
export const Dropdown: React.FC<DropdownProps< here >> = (props) => { ... }
答案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<T> {
items: {
title: string;
value: T;
}[];
defaultSelected?: number;
onSelected: (value: DropdownProps<T>["items"][number]["value"]) => void;
}
export const Dropdown = <T,>(props: DropdownProps<T>) => { ... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论