简体   繁体   English

记录<string, any>到 typescript 中的 {name: string}</string,>

[英]Record<string, any> to {name: string} in typescript

I have a custom react hook to do a API calls:我有一个自定义反应挂钩来执行 API 调用:

const useFetch: (string) => Record<string, any> | null = (path: string) => {
  const [data, setData] = useState<Record<string, any> | null>(null);

  var requestOptions: RequestInit = {
    method: "GET",
    redirect: "follow",
  };
  const fetcher = async () => {
    const res = await fetch(
      process.env.REACT_APP_API_ENDPOINT + path,
      requestOptions
    );
    const json = await res.json();
    setData(json.data);
  };
  useEffect(() => {
    fetcher();
  }, [path]);
  return data;
};

My problem is that I use this hook to call many different endpoints, so I cannot specify the type for data in the hook.我的问题是我使用这个钩子来调用许多不同的端点,所以我不能在钩子中指定data的类型。 But when I call the hook, I know what the data is for that specific endpoint, so I want to specify a type for the variable storing the return value like:但是当我调用钩子时,我知道该特定端点的数据是什么,所以我想为存储返回值的变量指定一个类型,例如:

const data: { name: string } | null = useFetch('/example-end-point');

This is what I want to achieve, but I get this error: Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'.这是我想要实现的目标,但我收到此错误: Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'. Property 'name' is missing in type 'Record<string, any>' but required in type '{ name: string; }'.

Using any for the return type works, but I don't want to resort to that if there are any other ways to achieve this.使用any作为返回类型是可行的,但如果有任何其他方法可以实现这一点,我不想诉诸于此。

This is something that Generic Types can solve, you can absolutely allow for variable types to be passed into your single hook with a little bit of a code re-write.这是 Generic Types 可以解决的问题,您绝对可以允许将变量类型传递到您的单个钩子中,只需重新编写一点代码。

Take a look...看一看...

const useFetch: <T>(string) => Record<T> | null = (path: string) => {
  const [data, setData] = useState<Record<T> | null>(null);

  var requestOptions: RequestInit = {
    method: "GET",
    redirect: "follow",
  };
  const fetcher = async () => {
    const res = await fetch(
      process.env.REACT_APP_API_ENDPOINT + path,
      requestOptions
    );
    const json = await res.json();
    setData(json.data);
  };
  useEffect(() => {
    fetcher();
  }, [path]);
  return data;
};

and then when you call it you can do the following.然后当你调用它时,你可以执行以下操作。

type MyData = {
  name: string,
}
const data: MyData | null = useFetch<MyData>('/example-end-point');

You'd probably want to use unknown instead of any then narrow down the type elsewhere by performing some type guarding ie您可能希望使用unknown而不是any然后通过执行一些类型保护来缩小其他地方的类型,即

const useFetch: (string) => unknown = (path: string) => {
...


const user = useFetch('/example-end-point')

if (!user || !user.name) throw new Error("Bad data")

const data: { name: string } = user

This way you get runtime data checking as well as type checking.通过这种方式,您可以获得运行时数据检查以及类型检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 记录和记录有什么区别<string, any>并记录<string, unkown>在 typescript 中?</string,></string,> - what's the difference between Record<string, any> and Record<string, unkown> in typescript? 字符串到打字稿类名 - String to typescript class name TypeScript - 计算属性名称的类型必须为“字符串”、“数字”、“符号”或“任意” - TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any' 记录之间的差异<string, any>和 {}? - Differences between Record<string, any> and {}? 如何防止 TypeScript 记录<string, any>从排序 object 属性到字母顺序?</string,> - How to prevent TypeScript Record<string, any> from sorting object properties to alphabetical order? TypeScript 类型'记录<string, string> ' 不可分配给类型 'string'</string,> - TypeScript Type 'Record<string, string>' is not assignable to type 'string' 模块名称字符串的 TypeScript 类型 - TypeScript type for module name string 记录之间的奇怪行为<string, unknown>并记录<string, any></string,></string,> - Weird behaviour between Record<string, unknown> and Record<string, any> 打字稿错误:计算的属性名称必须是“字符串”、“数字”、“符号”或“任何”类型 - Typescript error: A computed property name must be of type 'string', 'number', 'symbol', or 'any' 为什么可以录音<string, any>同等功能?</string,> - Why can Record<string, any> equal Functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM