Reputation: 1418
I have a json configuration file
[{ name: "apple", weight: 1.0 }, { name: "banana", weight: 2.0 }]
I create type that describes this configuration
type Config = { name: "apple" | "banana", weight: number }[];
Now I create a function that returns that configuration
import Configuration from './configuration.json';
function getConfig(): Config {
return Configuration;
}
I get error saying that
Type 'string' is not assignable to type '"apple" | "banana"'
I understand that the problem is with the field name
which type is resolved to string
and not "apple" | "banana"
.
It it possible to resolve .json
files with exact types? So that I can be sure that the .json
file has the correct structure using only TypeScript type system?
Upvotes: 1
Views: 311
Reputation: 785
It is a cast problem. Try casting it like this.
function getConfig(): Config {
return Configuration as Config;
}
Upvotes: 1