Issue
I have some piece of code, that generates a type from a json file and afterward performs some operations on it.
import data from './mydata.json'
type MyType = typeof data
....
This way I generate a type that very specifically fits the json, meaning the type will have the exact same keys as the json.
E.g. this json
{
"a" : "text",
"b" : {
"c" : "more text"
}
}
will create this type
{ a: string, b: { c: string } }
Since I use this piece of code across multiple projects, I'd like to extract it into a library. Each project has a different json, though.
Is there any way for me to pass the json from the project into the library, so that if I import MyType from the library it will have the exact keys as the json?
Solution
I was able to solve my problem using module augmentation
So in my library I defined an empty interface and made the required functions use this interface
export interface MyInterface {}
export myFunction = (param: string): MyInterface => {
...
}
Within my projects I then override the interface with the type of my local JSON
import { myFunction } from 'my-lib'
import data from './mydata.json'
declare module 'my-lib' {
type MyType = typeof data
export interface MyInterface extends MyType {}
}
const myResult = myFunction('lol')
This way I can be sure that the functions within the lib operate using the type of my local JSON data. So in the given example myResult will be of the type of the JSON.
Answered By - Bob Sheknowdas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.