[英]TypeScript resolve exact types from json file
I have a json configuration file我有一个 json 配置文件
[{ 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现在我创建一个返回该配置的 function
import Configuration from './configuration.json';
function getConfig(): Config {
return Configuration;
}
I get error saying that我得到错误说
Type 'string' is not assignable to type '"apple" |
类型 'string' 不可分配给类型 '"apple" | "banana"'
“香蕉”'
I understand that the problem is with the field name
which type is resolved to string
and not "apple" | "banana"
我知道问题出在类型被解析为
string
而不是"apple" | "banana"
的字段name
上。 "apple" | "banana"
. "apple" | "banana"
。
It it possible to resolve .json
files with exact types?是否可以使用精确类型解析
.json
文件? So that I can be sure that the .json
file has the correct structure using only TypeScript type system?这样我就可以确定
.json
文件具有正确的结构,仅使用 TypeScript 类型系统?
It is a cast problem.这是一个演员表问题。 Try casting it like this.
尝试像这样投射它。
function getConfig(): Config {
return Configuration as Config;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.