将 JSON 对象转换为 TypeScript 类型
将 JSON 对象转换为 TypeScript 类型
本文将介绍如何将一个 JSON 对象转换为 TypeScript 类型。
示例 JSON 对象:
{
"three": "Hello %s",
"num": {
"zero": "not cats",
"one": "only one cats",
"other": "is %d cats"
},
"num1": {
"zero": "not cats",
"one": "only one cats",
"other": "is %d cats"
},
"a": {
"b": {
"c": "s%2$s a %1$s"
},
"d": {
"c": "s%2$s a %1$s"
}
}
}
目标 TypeScript 类型:
interface Translation {
three: string;
num: {
zero: string;
one: string;
other: string;
};
num1: {
zero: string;
one: string;
other: string;
};
a: {
b: {
c: string;
};
d: {
c: string;
};
};
}
实现步骤:
- 创建 TypeScript 接口: 创建名为
Translation的接口,并根据 JSON 对象的结构定义接口属性及其类型。 - 将 JSON 对象转换为 TypeScript 类型: 由于 JSON 对象的结构与接口定义一致,可以直接将 JSON 对象赋值给
Translation接口类型的变量。
示例代码:
const jsonObject = {
'three': 'Hello %s',
'num': {
'zero': 'not cats',
'one': 'only one cats',
'other': 'is %d cats'
},
'num1': {
'zero': 'not cats',
'one': 'only one cats',
'other': 'is %d cats'
},
'a': {
'b': {
'c': 's%2$s a %1$s'
},
'd': {
'c': 's%2$s a %1$s'
}
}
};
const translation: Translation = jsonObject;
console.log(translation.three);
console.log(translation.num.zero);
console.log(translation.a.b.c);
注意:
- 在代码中,我们使用单引号
'来表示字符串,因为 TypeScript 中单引号和双引号都可以用于字符串。 - 如果 JSON 对象中的字段名和 TypeScript 接口属性名不一致,则需要使用
as关键字进行类型断言。
通过以上步骤,我们成功将 JSON 对象转换为 TypeScript 类型。这将帮助我们更好地组织代码,并进行类型检查,提高代码可读性和安全性。
原文地址: https://www.cveoy.top/t/topic/o4TT 著作权归作者所有。请勿转载和采集!