Let's say I have the following piece of code :
const value = JSON.parse('{"foo": "bar"}');
Here value
has type any
because of the JSON.parse
signature.
Considering the JSON.parse
function only has hard-coded argument(s) and has no side effects, it could be run successfully at compile time.
Can I ask TypeScript to evaluate this function at compile time, so it can provide me strong typing for the value
variable ?
CodePudding user response:
Someone implemented once a JSON parser in typescript I saw it here.
By taking his implementation of ParseJson
you can do something like this
function parseWithTypes<T extends string>(json: T) {
return JSON.parse(json) as ParseJson<T>;
}
const value = parseWithTypes('{"foo": "bar"}');
One caveat that it has is that it will infer the types as constant, meaning that the type foo
won't be string
but 'bar'
instead.
CodePudding user response:
Do you mean this?
interface Foo {
bar: string;
}
const value = <Foo>JSON.parse('{"foo": "bar"}');
const value1 = JSON.parse('{"foo": "bar"}') as Foo;