如何将对象键包含到通用类型中

问题描述 投票:0回答:1

enter image description here

您好,我有 tsx 的问题。我不知道如何编写泛型的类型。

在我的选项组件中,我有一个接口,它获取

display
display 是 T 的属性名称,值将作为字符串传递),它应该是 T 中的键。T 将保存 PETS 或 USERS 的数组。这里的
extends {id: string}
是为了确保PETS或者USERS有ID属性。

这些链接是我的参考。

https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#generic-components

谢谢您的帮助。

import React from "react";

interface IOptions<T, K extends keyof T> {
  display: K;
  values: T[];
}

const Options = <Y extends {id: string}, U>({values, display}: IOptions<Y, U>) => {
  return (
    <>
      {values.map((val: Y, index: number) => (
        <option key={index} value={val.id}>{val[display]}</option>
      ))}
    </>
  );
};

export default Options;

也尝试过这个:

<option key={index} value={val.id}>{val[display as keyof Y]}</option>
reactjs typescript typescript-generics react-typescript
1个回答
0
投票

类型“U”不满足约束“keyof Y”。

...并且:

类型“U”不能用于索引类型“Y”。

(屏幕截图中的

Y

您需要约束

U
,以便它也与
IOptions
中的约束兼容:

const Options = <Y extends { id: string }, U extends keyof Y>({ values, display }: IOptions<Y, U>) => {}

这直接解决了当前的两个错误,因为现在

U
明确是
Y
的键。

但是随后你会出现另一个错误:


类型“Y[U]”不可分配给类型“ReactNode”。

这是因为您仅将

Y
约束为
id
,但它的其他键可以有任何内容,特别是不适合渲染的值,例如:

const y = {
  id: "foo",
  bar: function () {} // Not suitable as ReactNode
} satisfies { id: string }

因此,您必须进一步约束泛型类型参数

Y
,以确保
Y[U]
可以被渲染,例如,如果 all 值为
ReactNode
:

const Options = <Y extends {
  id: string,
  [key: PropertyKey]: React.ReactNode
}, U extends keyof Y>({ values, display }: IOptions<Y, U>) => {}

游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.