簡體   English   中英

react/typescript 中的通用道具 - 如何讓 T 成為屬性的類型?

[英]Generic props in react/typescript - how to get T to be the type of a property?

我已經嘗試了無數的東西,但無法讓它工作

我有一個反應組件的道具, handleChange的類型應該是一個 function ,它接受作為values傳遞的任何內容。

type Props<T extends Record<string, unknown> = Record<string, unknown>> = {
   value: T,
   handleChange: (value: T) => void
}

我試圖讓 T 成為“ value的類型”,但在這個例子中,它們只是默認為Record ,這不是我想要的。

這是在材料 ui 中過度完成的(即自動完成)

TypeScript 具有強大的推理系統,它允許您無需手動指定泛型參數,而是根據運行時參數的類型對其進行分配。 對於 React + TypeScript,這看起來像:

type MyComponentProps<T extends Record<string, unknown>> = {
  value: T;
  handleChange: (value: T) => void;
};

const MyComponent = <T extends Record<string, unknown>>(
  props: MyComponentProps<T>
) => {
  return null;
};

class MyOtherComponent<
  T extends Record<string, unknown>
> extends React.Component<MyComponentProps<T>> {
  render() {
    return null;
  }
}
// This works
<MyComponent
  value={{ a: "hi", this: { is: "a", test: true } }}
  handleChange={(val) => {
    console.log("val.a =", val.a, "val.this =", val.this);
  }}
/>
<MyOtherComponent
  value={{ a: "hi", this: { is: "a", test: true } }}
  handleChange={(val) => {
    val.a = val.this.is;
  }}
/>
// This fails
<MyComponent
  value="not a Record<string, unknown>"
  handleChange={() => {}}
/>

代碼沙盒

暫無
暫無

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

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