TypeScriptでlibraryに型をつける
外部ライブラリにTypeScriptの型を付ける方法
無から外部型定義ファイルを作る
JSライブラリで、@types/hogeもなくて、全部自作する必要がある時
./types/hoge/index.d.tsを作ってそこに型定義を書く
hogeはライブラリの名前
code:ts
export function byteLength(encoded: string): number;
export function toByteArray(encoded: string): Uint8Array;
export function fromByteArray(bytes: Uint8Array): string;
tsconfig.jsonを修正する
code:tsconfig.json
{
"compilerOptions": {
"baseUrl": "./", // pathsを設定するために必要
"paths": {"hoge": "types/hoge"}, // hogeに対して、hogeの型定義ファイルの場所を指定
"typeRoots": "types", "node_modules/@types", // 型定義ファイルを見るときのpath
}
}
参考
TypeScript で型定義ファイル( d.ts )がないときの対処法 - Qiita
requireで読み込むのもある
最後の手段ではある
読んでないがこの辺も参考になるかも
dts-gen
JSから型を生成するやつ
https://github.com/Microsoft/dts-gen
MicroSoft製
https://qiita.com/ConquestArrow/items/450f961c3d54bc932cf3
更新されていない
型定義ファイルがあるが、一部を拡張して使いたい
code:ts
import 'react-redux'
import { StoreState } from '../store'
// ______________________________________________________
//
declare module 'react-redux' {
interface DefaultRootState extends StoreState {}
}
decrare moduleを使ってinterfaceを拡張する
拡張元の型がtype宣言とかになっていると無理
ちゃんとinterfaceで定義されていればできる
参考
react-redux の Hooks API に Generics は要らない - Qiita
https://typescript-jp.gitbook.io/deep-dive/project/modules/external-modules
prototype上書き
code:ts
declare module 'config' {
interface IConfig {
getTyped: <T extends Paths<ConfigType>>(key: T) => PathValue<ConfigType, T>;
}
}
const prototype: config.IConfig = Object.getPrototypeOf(config);
prototype.getTyped = config.get;
ここで見た
関連
TypeScriptの宣言空間
https://qiita.com/pentamania/items/200e4c09285c01f8917f
https://dev.classmethod.jp/articles/typings-of-window-object/
https://qiita.com/mtgto/items/e30d1529ca298e49557e