blog icon indicating copy to clipboard operation
blog copied to clipboard

获取 Types 的常见方法

Open nmsn opened this issue 3 years ago • 0 comments

来源:https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types

  1. 获取组件 props
import { Button } from "library"; // but doesn't export ButtonProps! oh no!
type ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!
type AlertButtonProps = Omit<ButtonProps, "onClick">; // modify
const AlertButton = (props: AlertButtonProps) => (
  <Button onClick={() => alert("hello")} {...props} />
);
  1. 获取函数返回值
// inside some library - return type { baz: number } is inferred but not exported
function foo(bar: string) {
  return { baz: 1 };
}

//  inside your app, if you need { baz: number }
type FooReturn = ReturnType<typeof foo>; // { baz: number }
  1. 获取函数参数
type FooParameters = Parameters<typeof foo>; // [bar:string]

对于更多的“自定义”,infer 关键字是为此的基本构建块

nmsn avatar Jul 11 '22 12:07 nmsn