typescript2.0 - 如何在 TypeScript 2.0/3.0 中添加自訂的「型別定義」
根據這篇文章,TypeScript 2.0 的 typings 系統已經改變,因此現在如何附加自訂 typings 尚不清楚。我是否應該總是為此建立 NPM 套件?
提前感謝你!
答案#1
你可以為你的專案建立本地自訂型別,在那裡你可以為 JS 函式庫聲明型別。為此,你需要:
建立目錄結構來保存你的型別宣告檔案,使你的目錄結構看起來類似於這樣:
. ├── custom_typings │ └── some-js-lib │ └── index.d.ts └── tsconfig.json在
index.d.ts文件中,為你的 JS 函式庫新增一個宣告:declare module 'some-js-lib' { export function hello(world: string): void }(可選:如果你的 TypeScript ≥ 4.x 可跳過) 在你的
tsconfig.json的compilerOptions區段中新增對此類型聲明的參考:{ "compilerOptions": { ... "typeRoots": ["./node_modules/@types", "./custom_typings"] }, ... }在你的程式碼中使用已宣告的模組:
import { hello } from 'some-js-lib' hello('world!')
