Global types in typescript

前端 未结 3 1809
囚心锁ツ
囚心锁ツ 2020-12-09 15:25

Is there a way to make a file in your typescript file that defines globally accessible types?

I like typescript but find that when i want to be truly type safe I hav

3条回答
  •  没有蜡笔的小新
    2020-12-09 16:20

    I found the accepted answer is not working (maybe it is some configuration that needs to be done?). So with some tinkering, I got it to work for me (maybe I also have some weird configuration option? Let me know if it doesn't work and I will remove this answer).

    1. Create a definition file in a suitable folder. I will be using types/global.d.ts
    2. Check your tsconfig.json and include "*": ["types/*.d.ts"] under paths. (You should also be able to directly address the created file if you care to).
    3. Put your global definitions directly into the root of the file NO declare global or similar.

    Now you should be good to go to use the types declared in this file (tested with typescript 3.9.6 and 3.7.5).

    Example file:

    // global.d.ts
    declare interface Foo {
        bar: string;
        fooBar: string;
    }
    

    What your tsconfig should look like:

    [...]
    "paths": {
        "*": ["types/*.d.ts"]
    },
    [...]
    

提交回复
热议问题