Skip to content

获取 Types 的常见方法 #20

@nmsn

Description

@nmsn

来源: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 关键字是为此的基本构建块

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions