[英]is there a library or a way to feed an object to and get a typescript type or interface implementation for that object?
所以我今年一直在使用 react 和 typescript,我注意到有时能够输入一些复杂的对象是多么困难。 因此,我想知道是否有一种方法或一个辅助函数,我们可以用一个对象调用并能够返回一个打字稿接口或一个类型,然后我们可以用它在我们的代码中编写它并将其用作每当我们使用对象时输入。
示例:假设我们有一个这样的对象:
const complexObject = {
"hsl": {
"h": 118.48101265822783,
"s": 1,
"l": 0.5,
"a": 1
},
"hex": "#06ff00",
"rgb": {
"r": 6,
"g": 255,
"b": 0,
"a": 1
},
"hsv": {
"h": 118.48101265822783,
"s": 1,
"v": 1,
"a": 1
},
"oldHue": 118.48101265822784
}
如您所见,键入此对象可能会有些麻烦,尤其是对于像我这样没有经验的开发人员而言。 现在如果有一个我们可以在这个上下文中调用getType
的库,那么我们可以做这样的事情:
getType(complexObject);
// return
type complexObject = {
hex: string;
hsl: { h: number; s: number; l: number; a: number };
hsv: { h: number; s: number; v: number; a: number };
rgb: { r: number; g: number; b: number; a: number };
};
如果您只想按照上面编写的getType
的方式在文件中使用类型,请按照Ozan 的答案使用typeof
。 尽管typeof
在运行时返回标准 JavaScript 中的字符串,但 TypeScript 赋予typeof
额外的含义:在类型表达式中,它允许您重用现有标识符的类型。
// Runs in the emitted JavaScript.
const someValue = typeof complexObject; // "object"
// Type only: not emitted to JavaScript.
type SomeType = typeof complexObject; // { hsl: { ... }, ... }
// Type only as well, because it's after the : so TS reads it as a type.
const typedValue: typeof complexObject = getComplexObject();
// field name: type expression = initial value
请记住,类型在运行时不存在,因此您不可能将类型作为运行时值或函数返回表达式(如getType
)返回。 像getType
这样的函数可能会返回一个值,并且该值可能具有有用的类型,但您不能使用函数返回类型本身。
旁注:如果您尝试基于现有 JavaScript 代码编写声明文件,或者如果您想获取接口定义以便将其复制粘贴到您自己的代码中,则标准工具是dts-gen .
您不需要像getType
这样的函数来检索类型作为变量并在代码中重用它。
您需要做的就是使用typeof
运算符并将该值分配给type
变量。
type ComplexObjectType = typeof complexObject;
现在,您可以使用ComplexObjectType
作为项目中其他变量的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.