简体   繁体   English

使用TypeScript接口进行类型转换

[英]Type conversion using TypeScript interface

This is kind of a weird question but I'm working on a massive form containing approximately ~100 input fields.这是一个奇怪的问题,但我正在处理一个包含大约 ~100 个输入字段的大型表单。 We're passing all this data to a GraphQL endpoint.我们将所有这些数据传递给 GraphQL 端点。 We're using TypeScript and I've defined Interfaces based on the schema.我们正在使用 TypeScript 并且我已经根据模式定义了接口。

I want to know if I can use TypeScript's interface types, to be specific the type boolean, to convert certain property values automatically to true or false since they arrive from the form as strings "1" or "0" , or "true" (checkboxes)?我想知道我是否可以使用 TypeScript 的接口类型,具体来说是 boolean 类型,将某些属性值自动转换为truefalse ,因为它们从表单以字符串"1""0""true" (复选框)? I could then build something of a filter/converter to convert certain input types for GraphQL requests automatically when I can detect it from the Interface.然后我可以构建一个过滤器/转换器的东西,当我可以从界面检测到它时,自动转换 GraphQL 请求的某些输入类型。 There was a suggestion to do something like this, here on StackOverflow:在 StackOverflow 上有人建议做这样的事情:

interface I1 {
    x: boolean; 
}

let myVar: I1['x'];

But you cannot use myVar as it is defined.但是您不能按定义使用myVar I would like to get typeof I1.x so I can get back 'boolean' and then do a conversion for some fields such as .!(obj.x) etc.我想获得typeof I1.x ,这样我就可以返回“boolean”,然后对某些字段进行转换,例如.!(obj.x)等。

So can I go about this or do I really have to generate a massive object tree converting or defining specific keys, again (duplication), to be boolean?那么我可以 go 关于这个还是我真的必须生成一个巨大的 object 树转换或定义特定的键,再次(重复),成为 boolean? Or do we have to think about using boolean values with GraphQ?或者我们是否必须考虑在 GraphQ 中使用 boolean 值?

I am not aware of a way to do the conversion using only interfaces, but could you not implement the interface in a class to achieve a similar outcome?我不知道只使用接口进行转换的方法,但是你不能在 class 中实现接口来实现类似的结果吗? Something along the lines of:类似的东西:

interface IOne {
    x : boolean
}

class One implements IOne {
    constructor(b_val?: boolean, b_str?: string) {
        if (b_val): this.x = b_val
        if (b_str) {
            if (b_str == 'true')
                this.x = true
            else
                this.x = false
        }
    }
}

Then you process input with new One(true, undefined) or new One(undefined, 'true') , etc. to get the conversion done for different input types, and you can pass the resulting object directly to anything that can consume the IOne interface.然后您使用new One(true, undefined)new One(undefined, 'true')等处理输入以完成不同输入类型的转换,您可以将生成的 object 直接传递给任何可以使用IOne的对象界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM