Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

获取 Types 的常见方法 #20

Open
nmsn opened this issue Jul 11, 2022 · 0 comments
Open

获取 Types 的常见方法 #20

nmsn opened this issue Jul 11, 2022 · 0 comments

Comments

@nmsn
Copy link
Owner

nmsn commented Jul 11, 2022

来源: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 nmsn changed the title 获取 types 的常见方法 获取 Types 的常见方法 Jul 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant