前沿
此文档根据官方”typescript如何与react结合“的英文版本,按行翻译而成, 可以与官方文档做比较。原文有很多丰富的案例,可以用来学习,根据理论与实践结合,会学习的更快。 小伙伴开始ts进阶吧。
所有使用指南关于react与ts【All react+typescript Cheatsheets】
- 基础篇【base】: 重点是帮助react的开发者在react apps中使用TS
- 侧重于自己我更好的练习,通过复制粘贴事例
- 解释一下基础TS-类型用法和配置过程
- 回到最常见的问题
- 没有详细介绍泛型类型逻辑。相反,我们更着重为新手教授简单的技术错误排查。
- 目标是在不学习太多TS的情况下有效利用TS。
- 进阶篇【advanced】:给大家介绍和解释一下通用类型的高级用法,编写可重用的类型实用程序/方法/渲染属性/高阶组件和TS + React库。
- 它还为专业用户提供了其他技巧。
- 有关对DefinitelyTyped做出贡献的建议
- 目标是充分利用TypeScript。
- 迁移篇【Migrating】: 有助于整理有关从JS或Flow进行迁移的大型代码库的建议。
- 我们不会试图说服人们进行切换,而只是帮助已经做出决定的人
- 这是一个新的速查表,欢迎您提供所有帮助
- 高阶篇【HOC】: 专门教大家用示例编写HOC(高阶组件)
基础篇【base】
配置
- 前提条件
- 你对react有很好的理解
- 熟悉TypeScript类型
- 请阅读官方的React文档中的TypeScript部分。
- react+typescript 入门套件
导入react
在TypeScript 2.7+中,您可以使用—allowSyntheticDefaultImports运行TypeScript(或在tsconfig中添加“ allowSyntheticDefaultImports”:true)以像在常规jsx中那样进行导入:
import * as React from "react";import * as ReactDOM from "react-dom";
入门
Function Components
这些可以编写为带有props参数并返回JSX元素的普通函数。
type AppProps = { message: string }; /* could also use interface */const App = ({ message }: AppProps) => <div>{message}</div>;
您还可以使用React.FunctionComponent(或简写的React.FC)编写组件:
const App: React.FC<{ message: string }> = ({ message }) => (<div>{message}</div>);
与“正常 function”版本有所不同:
- 它为displayName,propTypes和defaultProps等静态属性提供类型检查和自动完成功能,但是,当前将defaultProps与React.FunctionComponent一起使用时存在一些已知问题,有关详细信息,请参见 this issue for details (向下滚动到我们的defaultProps部分)
- 它提供了children的隐式定义 (见下文 see blow)
const Title: React.FunctionComponent<{ title: string }> = ({children,title}) => <div title={title}>{children}</div>;
- 将来,它可能会自动将props标记为只读,但是如果在参数列表中销毁了props对象,那将是一个有争议的问题。
- React.FunctionComponent对于返回类型是显式的(需要明确返回的值类型),而普通函数版本是隐式的(否则需要附加注释)。
在大多数情况下,使用哪种语法几乎没有什么区别,但是React.FC语法稍微冗长一些,但没有提供明显的优势,因此优先考虑了“普通函数”语法。
小陷阱
不支持这些模式:
- 条件渲染
这是因为由于编译器的限制,功能组件不能返回除JSX表达式或null以外的任何内容,否则它会发出一条隐秘的错误消息,指出无法将其他类型分配给Element,从而产生报错
const MyConditionalComponent = ({ shouldRender = false }) =>shouldRender ? <div /> : false; // don't do this in JS eitherconst el = <MyConditionalComponent />; // throws an error
Array.fill
不幸的是,仅注释函数类型将无济于事,因此,如果您确实需要返回React支持的其他奇异类型,则需要执行类
型断言:
const MyArrayComponent = () => Array(5).fill(<div />);const el2 = <MyArrayComponent />; // throws an error
// 需要用as JSX.Element注解const MyArrayComponent = () => (Array(5).fill(<div />) as any) as JSX.Element;
Hooks demo参考
从v16.8开始,@ types / react中支持Hooks。
useState
在大多数情况下,类型推理非常有效:
const [val, toggle] = React.useState(false); // `val` is inferred to be a boolean, `toggle` only takes booleans
如果您需要使用依赖于推理的复杂类型,另请参见使用推断的类型部分。
然而,许多Hooks 都使用带有空值的默认值初始化,如何提供类型?明确声明类型,并使用联合类型:
const [user, setUser] = React.useState<IUser | null>(null);// later...setUser(newUser);
useRef
使用useRef时,在创建没有初始值的ref容器时,有两个选择:
// 将ref1.current设为只读,并打算传递给React将管理的内置ref属性(因为React会为您设置当前值)。const ref1 = useRef<HTMLElement>(null!);// 将使ref2.current可变,并且用于您自己管理的“实例变量”。const ref2 = useRef<HTMLElement | null>(null);
use: 在typescript编译链接器中参考
function TextInputWithFocusButton() {// initialise with null, but tell TypeScript we are looking for an HTMLInputElementconst inputEl = React.useRef<HTMLInputElement>(null);const onButtonClick = () => {// strict null checks need us to check if inputEl and current exist.// but once current exists, it is of type HTMLInputElement, thus it// has the method focus! ✅if (inputEl && inputEl.current) {inputEl.current.focus();}};return (<>{/* in addition, inputEl only can be used with input elements. Yay! */}<input ref={inputEl} type="text" /><button onClick={onButtonClick}>Focus the input</button></>);}
useEffect
使用useEffect时,请注意不要返回任何非函数或未定义的内容, 否则TypeScript和React都会报错,
使用箭头功能时要当心
function DelayedEffect(props: { timerMs: number }) {const { timerMs } = props;//报错!setTimeout隐式返回一个数字,因为箭头函数主体未用大括号括起来useEffect(() =>setTimeout(() => {/* do stuff */}, timerMs),[timerMs]);return null;}
useReducer
你可以为 reducer actions 使用连符区分, 不要忘记定义reducer的返回类型,否则Typescript会推断出来。
type AppState = {};type Action =| { type: "SET_ONE"; payload: string }| { type: "SET_TWO"; payload: number };export function reducer(state: AppState, action: Action): AppState {switch (action.type) {case "SET_ONE":return {...state,one: action.payload // `payload` is string};case "SET_TWO":return {...state,two: action.payload // `payload` is number};default:return state;}}
Custom Hooks(自定义Hooks)
如果要在“Custon Hooks”中返回数组,当您实际上希望在数组的每个位置使用不同的类型时,则将要避免类型推断,由于Typescript会结合类型推断。相反,请使用TS 3.4 const断言:
这样,当您进行解构时,实际上会根据解构位置获得正确的类型:
export function useLoading() {const [isLoading, setState] = React.useState(false);const load = (aPromise: Promise<any>) => {setState(true);return aPromise.finally(() => setState(false));};return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]}
替代方案:声明元组返回类型
如果您在使用const断言时遇到麻烦,还可以断言或定义函数返回类型:
export function useLoading() {const [isLoading, setState] = React.useState(false);const load = (aPromise: Promise<any>) => {setState(true);return aPromise.finally(() => setState(false));};return [isLoading, load] as [boolean,(aPromise: Promise<any>) => Promise<any>];}
如果您编写了许多自定义钩子,则自动键入元组的辅助函数也可能会有所帮助:
function tuplify<T extends any[]>(...elements: T) {return elements;}function useArray() {const numberValue = useRef(3).current;const functionValue = useRef(() => {}).current;return [numberValue, functionValue]; // type is (number | (() => void))[]}function useTuple() {const numberValue = useRef(3).current;const functionValue = useRef(() => {}).current;return tuplify(numberValue, functionValue); // type is [number, () => void]}
注意,React团队建议返回两个以上值的自定义钩子应该使用适当的对象而不是元组
更多Hooks + TypeScript阅读:
- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d
- https://fettblog.eu/typescript-react/hooks/#useref
如果您正在编写React Hooks库,请不要忘记还应该公开您的类型供用户使用。
示例React Hooks + TypeScript库:
- https://github.com/mweststrate/use-st8
- https://github.com/palmerhq/the-platform
- https://github.com/sw-yx/hooks
Class Components
在TypeScript中,React.Component是泛型类型(aka React.Component
type MyProps = {// using `interface` is also okmessage: string;};type MyState = {count: number; // like this};class App extends React.Component<MyProps, MyState> {state: MyState = {// optional second annotation for better type inferencecount: 0};render() {return (<div>{this.props.message} {this.state.count}</div>);}}
不要忘记,您可以导出/导入/扩展这些类型/接口以供重用。
Class Methods
像平常一样做,但是要记住您的函数的任何参数也需要输入:
class App extends React.Component<{ message: string }, { count: number }> {state = { count: 0 };render() {return (<div onClick={() => this.increment(1)}>{this.props.message} {this.state.count}</div>);}increment = (amt: number) => {// like thisthis.setState(state => ({count: state.count + amt}));};}
Class Properties
如果需要声明类属性以供以后使用,则只需像状态一样声明它,但无需分配:
class App extends React.Component<{message: string;}> {pointer: number; // like thiscomponentDidMount() {this.pointer = 3;}render() {return (<div>{this.props.message} and {this.pointer}</div>);}}
Typing defaultProps
对于Typescript 3.0+,类型推断应该起作用,尽管某些边缘情况仍然存在问题。只需像平常一样键入您的道具,除了不使用React.FC。
// ////////////////// function components// ////////////////type Props = { age: number } & typeof defaultProps;const defaultProps = {who: "Johny Five"};const Greet = (props: Props) => {/*...*/};Greet.defaultProps = defaultProps;
对于Class组件,有几种方法可以做到这一点(包括使用Pick实用程序类型),但是建议定义props:
type GreetProps = typeof Greet.defaultProps & {age: number;};class Greet extends React.Component<GreetProps> {static defaultProps = {name: "world"};/*...*/}// Type-checks! No type assertions needed!let el = <Greet age={3} />;
Why does React.FC break defaultProps?
You can check the discussions here:
- https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680
- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695
- https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/87
这只是当前状态,将来可能会解决。
Types or Interfaces?(types或者interfaces怎么选择?)
interface与TypeScript中的types不同, 但是就普通的React用例而言,它们的使用是非常相似的,这里有一些有用的经验法则
- 在创作库或第三方环境类型定义时,始终使用接口作为公共API的定义
- 考虑将types用于您的React Component Props和State,因为它更受限制。
types对于联合类型非常有用(例如,类型MyType = TypeA | TypeB),而Interfaces则更适合于声明dictionary shapes(????) ,然后实现或扩展它们。
types与interfaces的使用表格

Basic Prop Types Examples
type AppProps = {message: string;count: number;disabled: boolean;/** array of a type! */names: string[];/** string literals to specify exact string values, with a union type to join them together */status: "waiting" | "success";/** any object as long as you dont use its properties (not common) */obj: object;obj2: {}; // almost the same as `object`, exactly the same as `Object`/** an object with defined properties (preferred) */obj3: {id: string;title: string;};/** array of objects! (common) */objArr: {id: string;title: string;}[];/** any function as long as you don't invoke it (not recommended) */onSomething: Function;/** function that doesn't take or return anything (VERY COMMON) */onClick: () => void;/** function with named prop (VERY COMMON) */onChange: (id: number) => void;/** alternative function type syntax that takes an event (VERY COMMON) */onClick(event: React.MouseEvent<HTMLButtonElement>): void;/** an optional prop (VERY COMMON!) */optional?: OptionalType;};
Useful React Prop Type Examples
export declare interface AppProps {children1: JSX.Element; // bad, doesnt account for arrayschildren2: JSX.Element | JSX.Element[]; // meh, doesnt accept functionschildren3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utilitychildren4: React.ReactChild[]; // betterchildren: React.ReactNode; // best, accepts everythingfunctionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop typestyle?: React.CSSProperties; // to pass through style propsonChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.targetprops: Props & React.PropsWithoutRef<JSX.IntrinsicElements["button"]>; // to impersonate all the props of a button element without its ref}
JSX.Element vs React.ReactNode?
一个更技术性的解释是,有效的React节点与React.createElement返回的不是相同的东西。无论组件最终呈现什么内容,React.createElement始终返回一个对象,即JSX.Element接口,但是React.ReactNode是组件所有可能的返回值的集合。
JSX.Element-> Return value ofReact.createElementReact.ReactNode-> Return value of a component
getDerivedStateFromProps
在开始使用getDerivedStateFromProps之前,请仔细阅读文档,您可能不需要派生状态,
您可以通过以下几种方式进行注释getDerivedStateFromProps
- 如果您已明确键入派生状态,并希望确保getDerivedStateFromProps的返回值与之一致。
class Comp extends React.Component<Props, State> {static getDerivedStateFromProps(props: Props,state: State): Partial<State> | null {//}}
- 当您希望函数的返回值确定状态时
class Comp extends React.Component<Props,ReturnType<typeof Comp["getDerivedStateFromProps"]>> {static getDerivedStateFromProps(props: Props) {}}
- 当您想要具有其他状态字段和备注的派生状态
type CustomValue = any;interface Props {propA: CustomValue;}interface DefinedState {otherStateField: string;}type State = DefinedState & ReturnType<typeof transformPropsToState>;function transformPropsToState(props: Props) {return {savedPropA: props.propA, // save for memoizationderivedState: props.propA};}class Comp extends React.PureComponent<Props, State> {constructor(props: Props) {super(props);this.state = {otherStateField: "123",...transformPropsToState(props)};}static getDerivedStateFromProps(props: Props, state: State) {if (isEqual(props.propA, state.savedPropA)) return null;return transformPropsToState(props);}}
Forms and Events
如果性能不是问题,则内联处理程序是最简单的,因为您可以使用类型推断和上下文类型输入:
const el = (<buttononClick={event => {/* ... */}}/>);
但是,如果您需要单独定义事件处理程序,那么IDE工具确实非常有用,因为@type定义带有大量的键入功能。输入您要查找的内容,通常自动完成功能会为您提供帮助。这是表单事件的onChange:
class App extends React.Component<{},{// no propstext: string;}> {state = {text: ""};// typing on RIGHT hand side of =onChange = (e: React.FormEvent<HTMLInputElement>): void => {this.setState({ text: e.currentTarget.value });};render() {return (<div><input type="text" value={this.state.text} onChange={this.onChange} /></div>);}}
您可以选择将类型应用于事件处理程序本身(由@TomasHubelbauer提供),而不是使用React.FormEvent <>和void来键入参数和返回值:
// typing on LEFT hand side of =onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {this.setState({text: e.currentTarget.value})}
为什么两种方法可以做同一件事?
第一个方法使用推断的方法签名(例如:React.FormEvent
onSubmit事件类型,表单中包含不受控制的组件
如果您不太关心事件的类型,则可以使用React.SyntheticEvent。如果您的目标表单具有要访问的自定义命名输入,则可以使用宽泛类型:
<formref={formRef}onSubmit={(e: React.SyntheticEvent) => {e.preventDefault();const target = e.target as typeof e.target & {email: { value: string };password: { value: string };};const email = target.email.value; // typechecks!const password = target.password.value; // typechecks!// etc...}}><div><label>Email:<input type="email" name="email" /></label></div><div><label>Password:<input type="password" name="password" /></label></div><div><input type="submit" value="Log in" /></div></form>
Context
使用React.createContext和上下文获取器(context getter )创建一个没有defaultValue的createCtx,无需检查未定义的内容:
// create context with no upfront defaultValue// without having to do undefined check all the timefunction createCtx<A>() {const ctx = React.createContext<A | undefined>(undefined);function useCtx() {const c = React.useContext(ctx);if (!c) throw new Error("useCtx must be inside a Provider with a value");return c;}return [useCtx, ctx.Provider] as const; // make TypeScript infer a tuple, not an array of union types}// usageexport const [useCtx, SettingProvider] = createCtx<string>(); // specify type, but no need to specify value upfront!export function App() {const key = useCustomHook("key"); // get a value from a hook, must be in a componentreturn (<SettingProvider value={key}><Component /></SettingProvider>);}export function Component() {const key = useCtx(); // can still use without null check!return <div>{key}</div>;}
使用React.createContext和useContext来创建带有未声明状态的上下文设置器的createCtx:
export function createCtx<A>(defaultValue: A) {type UpdateType = React.Dispatch<React.SetStateAction<typeof defaultValue>>;const defaultUpdate: UpdateType = () => defaultValue;const ctx = React.createContext({state: defaultValue,update: defaultUpdate});function Provider(props: React.PropsWithChildren<{}>) {const [state, update] = React.useState(defaultValue);return <ctx.Provider value={{ state, update }} {...props} />;}return [ctx, Provider] as const; // alternatively, [typeof ctx, typeof Provider]}// usageconst [ctx, TextProvider] = createCtx("someText");export const TextContext = ctx;export function App() {return (<TextProvider><Component /></TextProvider>);}export function Component() {const { state, update } = React.useContext(TextContext);return (<label>{state}<input type="text" onChange={e => update(e.target.value)} /></label>);}
Class component wrapper use Context
interface ProviderState {themeColor: string;}interface UpdateStateArg {key: keyof ProviderState;value: string;}interface ProviderStore {state: ProviderState;update: (arg: UpdateStateArg) => void;}const Context = React.createContext({} as ProviderStore); // type assertion on empty objectclass Provider extends React.Component<{}, ProviderState> {public readonly state = {themeColor: "red"};private update = ({ key, value }: UpdateStateArg) => {this.setState({ [key]: value });};public render() {const store: ProviderStore = {state: this.state,update: this.update};return (<Context.Provider value={store}>{this.props.children}</Context.Provider>);}}const Consumer = Context.Consumer;
forwardRef/createRef
检查Hooks section 部分的useRef。More info: https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315createRef:
class CssThemeProvider extends React.PureComponent<Props> {private rootRef = React.createRef<HTMLDivElement>(); // like thisrender() {return <div ref={this.rootRef}>{this.props.children}</div>;}}
forwardRef:
type Props = { children: React.ReactNode; type: "submit" | "button" };export type Ref = HTMLButtonElement;export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (<button ref={ref} className="MyClassName" type={props.type}>{props.children}</button>));
Portals
Using ReactDOM.createPortal:
const modalRoot = document.getElementById("modal-root") as HTMLElement;// assuming in your html file has a div with id 'modal-root';export class Modal extends React.Component {el: HTMLElement = document.createElement("div");componentDidMount() {modalRoot.appendChild(this.el);}componentWillUnmount() {modalRoot.removeChild(this.el);}render() {return ReactDOM.createPortal(this.props.children, this.el);}}
Context of Example
This example is based on the Event Bubbling Through Portal example of React docs.
进阶篇
Union Types and Type Guarding
联合类型对于解决其中一些打字问题非常方便:
class App extends React.Component<{},{count: number | null; // like this}> {state = {count: null};render() {return <div onClick={() => this.increment(1)}>{this.state.count}</div>;}increment = (amt: number) => {this.setState(state => ({count: (state.count || 0) + amt}));};}
Type Guarding:
Sometimes Union Types solve a problem in one area but create another downstream. If A and B are both object types, A | B isn’t “either A or B”, it is “A or B or both at once”, which causes some confusion if you expected it to be the former. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:
interface Admin {role: string;}interface User {email: string;}// Method 1: use `in` keywordfunction redirect(user: Admin | User) {if ("role" in user) {// use the `in` operator for typeguards since TS 2.7+routeToAdminPage(user.role);} else {routeToHomePage(user.email);}}// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enoughfunction isAdmin(user: Admin | User): user is Admin {return (user as any).role !== undefined;}
方法2也称为用户定义类型防护,对于可读代码来说真的很方便。TS本身就是通过typeof和instanceof来优化类型的。
如果需要if … else链或switch语句,则它应该“正常工作”,但如果需要帮助,请查找 Discriminated Unions。(See also: Basarat’s writeup)。这对于useReducer或Redux的 typing reducers 非常方便。
Optional Types
如果组件具有可选的props,则添加一个问号并在获取值时分配(或使用defaultProps)。
class MyComponent extends React.Component<{message?: string; // like this}> {render() {const { message = "default" } = this.props;return <div>{message}</div>;}}
Enum Types
TypeScript中的枚举默认为数字。通常,您通常希望将它们用作字符串:
export enum ButtonSizes {default = "default",small = "small",large = "large"}
Usage:
export const PrimaryButton = (props: Props & React.HTMLProps<HTMLButtonElement>) => <Button size={ButtonSizes.default} {...props} />;
枚举的一个更简单的替代方法是使用union声明一串字符串:
export declare type Position = "left" | "right" | "top" | "bottom";
Type Assertion(类型断言)
有时,与TypeScript相比,您更清楚地知道所使用的类型比其想像的要窄,或者需要将联合类型声明为更特定的类型才能与其他API一起使用,因此请使用as关键字进行声明。这告诉编译器您比它了解的更多
class MyComponent extends React.Component<{message: string;}> {render() {const { message } = this.props;return (<Component2 message={message as SpecialMessageType}>{message}</Component2>);}}
您还可以在访问属性时断言属性为非空:
element.parentNode!.removeChild(element) // ! before the periodmyFunction(document.getElementById(dialog.id!)! // ! after the property accessinglet userID!: string // definite assignment assertion... be careful!
Simulating Nominal Types(模拟types类型)
TS的结构化类型非常方便,直到不方便为止。但是,您可以使用品牌商标模拟名义输入:?????
type OrderID = string & { readonly brand: unique symbol };type UserID = string & { readonly brand: unique symbol };type ID = OrderID | UserID;
我们可以使用“伴侣对象模式”创建这些值:
function OrderID(id: string) {return id as OrderID;}function UserID(id: string) {return id as UserID;}
现在,TypeScript将禁止您在错误的位置使用错误的ID:
function queryForUser(id: UserID) {// ...}queryForUser(OrderID("foobar")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'
Intersection Types(交叉类型)
将两种类型加在一起可能很方便,例如,当您的组件像按钮HTMLButtonElement+本地组件的props时:
export interface Props {label: string;}export const PrimaryButton = (props: Props & React.HTMLProps<HTMLButtonElement> // adding my Props together with the @types/react button provided props) => <Button {...props} />;
您还可以使用“交集类型”使类似组件的props可重用子集:
type BaseProps = {className?: string,style?: React.CSSPropertiesname: string // used in both}type DogProps = {tailsCount: number}type HumanProps = {handsCount: number}export const Human: React.FC<BaseProps & HumanProps> = // ...export const Dog: React.FC<BaseProps & DogProps> = // ...
重载函数类型(Overloading Function Types)
特别是在函数方面,您可能需要重载而不是联合类型。编写函数类型的最常见方式是使用速记:
type FunctionType1 = (x: string, y: number) => number;
但这不会让您做任何重载。如果有实现,则可以使用function关键字将它们放在后面:
function pickCard(x: { suit: string; card: number }[]): number;function pickCard(x: number): { suit: string; card: number };function pickCard(x): any {// implementation with combined signature// ...}
但是,如果您没有实现,而只是编写.d.ts定义文件,那么这也将无济于事。在这种情况下,您可以放弃任何速记并以老式的方式编写它们。这里要记住的关键是就TypeScript而言,函数只是没有键的可调用对象:
type pickCard = {(x: { suit: string; card: number }[]): number;(x: number): { suit: string; card: number };// no need for combined signature in this form// you can also type static properties of functions here eg `pickCard.wasCalled`};
Using Inferred Types
依靠Typescript的类型推断非常有用……直到您意识到需要推断出的类型,并且必须回过头来明确declare types/interfaces,以便可以导出它们以进行重用。幸运的是,有了typeof,您将不必这样做。只需将其用于任何值即可:
const [state, setState] = React.useState({foo: 1,bar: 2}); // state's type inferred to be {foo: number, bar: number}const someMethod = (obj: typeof state) => {// grabbing the type of state even though it was inferred// some code using objsetState(obj); // this works};
types不需要导出
这可能很烦人,但是这里有几种获取类型的方法!
- 捕获组件的Prop类型:使用React.ComponentProps和typeof,并可选地忽略任何重叠类型
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">; // modifyconst AlertButton: React.FC<AlertButtonProps> = props => (<Button onClick={() => alert("hello")} {...props} />);
您也可以使用ComponentPropsWithoutRef(而不是ComponentProps)和ComponentPropsWithRef(如果您的组件专门转发参考)
- 获取函数的返回类型:使用ReturnType
function foo(bar: string) {return { baz: 1 };}// inside your app, if you need { baz: number }type FooReturn = ReturnType<typeof foo>; // { baz: number }
实际上,您几乎可以获取任何公共类型
function foo() {return {a: 1,b: 2,subInstArr: [{c: 3,d: 4}]};}type InstType = ReturnType<typeof foo>;type SubInstArr = InstType["subInstArr"];type SubIsntType = SubInstArr[0];let baz: SubIsntType = {c: 5,d: 6 // type checks ok!};//You could just write a one-liner,//But please make sure it is forward-readable//(you can understand it from reading once left-to-right with no jumps)type SubIsntType2 = ReturnType<typeof foo>["subInstArr"][0];let baz2: SubIsntType2 = {c: 5,d: 6 // type checks ok!};
故障排除手册:图像和其他非TS / TSX文件
Use declaration merging:
// declaration.d.ts// anywhere in your project, NOT the same name as any of your .ts/tsx filesdeclare module "*.png";// importing in a tsx fileimport * as logo from "./logo.png";
请注意,tsc无法为您捆绑这些文件,您将不得不使用Webpack或Parcel。
故障排除手册:Operators(操作符)
typeofandinstanceof: 具体的类型查询keyof: 获取对象的keyO[K]: 属性查询[K in O]:类型映射+or-orreadonlyor?: 加减法,只读和可选修饰符x ? Y : Z: 泛型类型,类型别名,函数参数类型的条件类型!: 可为空的类型的非空声明=: 通用类型的通用类型参数默认值as: 类型断言is: 函数返回类型的类型防护
条件类型是一个很难解决的话题,因此这里有一些额外的资源:
- fully walked through explanation https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/
- Bailing out and other advanced topics https://github.com/sw-yx/ts-spec/blob/master/conditional-types.md
故障排除手册:实用程序
这些都是内置的see source in es5.d.ts:
ConstructorParameters: 类构造函数的参数类型的元组Exclude: 从另一个类型中排除一个类型Extract: 选择可分配给另一种类型的子类型InstanceType: 从类构造函数的更新中获得的实例类型NonNullable:从类型中排除null和undefinedParameters: 函数参数类型的元组Partial: 将对象中的所有属性设为可选Readonly: 使对象中的所有属性为只读ReadonlyArray: 制作给定类型的不可变数组Pick: 对象类型的子类型及其键的子集Record: 从键类型到值类型的映射Required: 使对象中的所有属性为必需ReturnType: 函数的返回类型
故障排除手册:TSLint
注意:TSLint正在维护中,ESLint是TypeScript的前进之路
有时TSLint只是阻碍了您的前进。明智地关闭事物可能会有所帮助。您可以使用以下有用的tslint禁用:
/* tslint:disable */完全禁用// tslint:disable-line仅禁用当前行/* tslint:disable:semicolon */禁用prettier设置的结尾为分号属性/* tslint:disable:no-any */当您想使用任何时禁用tslint限制/* tslint:disable:max-line-length */禁用最大行数
故障排除手册:tsconfig.json
您可以在Typescript文档中找到所有的Compiler选项。这是我为APPS滚动的设置(不是库-对于您可能希望查看我们在tsdx中使用的设置的库):
{"compilerOptions": {"incremental": true,"outDir": "build/lib","target": "es5","module": "esnext","lib": ["dom", "esnext"],"sourceMap": true,"importHelpers": true,"declaration": true,"rootDir": "src","strict": true,"alwaysStrict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"allowJs": false,"jsx": "react","moduleResolution": "node","baseUrl": "src","forceConsistentCasingInFileNames": true,"esModuleInterop": true,"suppressImplicitAnyIndexErrors": true,"allowSyntheticDefaultImports": true,"experimentalDecorators": true},"include": ["src/**/*"],"exclude": ["node_modules", "build", "scripts"]}
所选标志以及我们为什么喜欢它们:
esModuleInterop: 禁用命名空间导入 (import * as foo from "foo") and 启用 CJS/AMD/UMD 类型导入(import fs from "fs")strict:strictPropertyInitialization强制您初始化类属性或显式声明它们可以是未定义的. 您可以使用明确的分配断言选择退出"typeRoots": ["./typings", "./node_modules/@types"]: By default, TypeScript looks innode_modules/@typesand parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a specialtypingsfolder.
故障排除手册:官方输入中的错误
如果您只需要添加一个接口或向现有接口添加缺少的成员,则无需复制整个输入程序包。相反,您可以使用声明合并:
// my-typings.tsdeclare module "plotly.js" {interface PlotlyHTMLElement {removeAllListeners(): void;}}// MyComponent.tsximport { PlotlyHTMLElement } from "plotly.js";const f = (e: PlotlyHTMLElement) => {e.removeAllListeners();};
您不必总是实现模块,只需将模块导入为快速入门即可:
// my-typings.tsdeclare module "plotly.js"; // each of its imports are `any`
因为您不必显式导入它,所以这称为环境模块声明。您可以在脚本模式下的.ts文件(无导入或导出)或项目中任何位置的.d.ts文件中使用AMD。
您还可以执行环境变量和环境类型声明:
// ambient utiltity typetype ToArray<T> = T extends unknown[] ? T : T[];// ambient variabledeclare let process: {env: {NODE_ENV: "development" | "production";};};process = {env: {NODE_ENV: "production"}}
编辑器工具和集成
- VSCode
- swyx’s VSCode Extension: https://github.com/sw-yx/swyx-react-typescript-snippets
- amVim: https://marketplace.visualstudio.com/items?itemName=auiworks.amvim
- VIM
- https://github.com/Quramy/tsuquyomi
- nvim-typescript?
- https://github.com/leafgarland/typescript-vim
- peitalin/vim-jsx-typescript
- NeoVim: https://github.com/neoclide/coc.nvim
- other discussion: https://mobile.twitter.com/ryanflorence/status/1085715595994095620
