React + TypeScript等ではまったこと

React, TypeScript
2019-08-01

TypeScriptでReactの開発をしているときにハマった箇所のメモ。

ReactのイベントのProps定義

クリックイベントはReact.MouseEvent、選択リスト/テキストのインプットはReact.ChangeEventが型になる。

export interface IMyComponentProps {
   prop1: string;
   prop2: (event: React.MouseEvent) => void; // ← 🈁
}

export class MyComponent extends React.Component<IMyComponentProps> {
    render(): JSX.Element {
        const { prop1, prop2 } = this.props

        return (
            //My code here
            <button onClick={prop2}>{prop1}</button>
        );
    }
}

creatRefの書き方

class MyComponent extends React.Component<{}, {} > {
  input: React.RefObject<HTMLInputElement>;

  constructor(props: InputTextProps) {
    super(props);
    this.input = React.createRef();
  }
  ...
}

JavaScriptのGoogle Map APIの型定義

$ npm install  @types/googlemaps -D
import {} from 'googlemaps';

const map: google.maps.Map = new google.maps.Map(...);
"message": "ファイル '.../node_modules/@types/googlemaps/index.d.ts' はモジュールではありません。",

というエラーがでるので

types/index.d.ts に以下を追加

declare module 'googlemaps'

Promiseを返す関数

おまけですが。

Returning a promise in an async function in TypeScript - Stack Overflow

const whatever2 = async (): Promise<number> => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};
Written by Kyohei Tsukuda who lives and works in Tokyo 🇯🇵 , building useful things 🔧.