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"
"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?
It is a cast problem. Try casting it like this.
function getConfig(): Config {
return Configuration as Config;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.