【问题标题】:React-Typescript: How to write interface with conditional statementReact-Typescript:如何使用条件语句编写接口
【发布时间】:2021-12-21 21:37:30
【问题描述】:

我正在尝试使用带有条件语句的接口。

在一个界面中,我知道我们可以在下面有这样的东西来设置条件。

interface exampleInterface {
    a: 'A' | 'B'
}

这样,我们可以确保输入“a”必须是“A”或“B”。 我想从 ['A', 'B'] 之类的数组中填充这种条件

下面有什么方法可以做到吗?

const a_list = Object.keys(config.a_list) // ['A', 'B'] I want to generate this from the config file.
interface exampleInterface {
    a: oneOf(a_list)
}

我想这样的原因是输入数组是动态的(从配置文件中获取信息)。 任何想法或建议都会有所帮助。谢谢。


其他信息: 我已经从配置文件创建了数组,并在界面中执行了以下操作。

interface myInterface {
    a: typeof a_list[number],
}

但是当我尝试从如下用户输入的配置文件中获取信息时,我收到以下错误。

export default function myFunc(props: myInterface)
    const [a] = useState(config.a_config[props.a].map((a) => a))

// Element implicitly has an 'any' type because the expression of type 'string' can't be used to index type.
//  No index signature with a parameter of type 'string' was found on the type.

【问题讨论】:

  • 你用过enum吗?您可以定义它,然后在道具中使用类似的类型
  • 不是来自配置。只有const a_list = ['A', 'B'] as const,然后是a: typeof a_list[number]

标签: reactjs typescript dynamic interface


【解决方案1】:

也许是一个枚举数组

这是一个有用的链接:https://stackoverflow.com/a/56036508/17364288

enum MyEnum {
    A = 'foo',
    B = 'bar'
}

interface exampleInterface {
    a: MyEnum[]
}

【讨论】:

    【解决方案2】:

    这完全取决于您要使用的配置类型。 要进行工作类型检查,您的配置必须在编译/类型检查时可读,所以第一个解决方案是使用 JSON 文件,并导入它。

    那么你的任务可以转换成两个:

    文件:simple.json 作为配置

    {
      "union": ["A", "B", "C"], 
      "x": { "a": 1, "b": 1, "c": 1 }
    }
    

    文件:importJsonAsConfig.ts 在 tsconfig 中需要 "resolveJsonModule": true

    import configFromJson from "./simple.json";
    
    type abUnionFromJson = keyof typeof configFromJson.x;
    //                   = "a" | "b" | "c"
    
    

    我没有设法获得工会工作,但 JSON 格式的地图工作正常。

    那么如果你有 JSON config 你可以将它转换成 js/ts 并更舒适地编写配置;

    文件:simpleConfig.ts

    const config = {
      union: ["A", "B", "C"],
    } as const; //ts config needed for this as const
    export default config;
    

    文件:importJsonAsConfig.ts

    import tsConfig from "./simpleConfig";
    type ABTulupeFromTs = typeof tsConfig.union;
    type AB = ABTulupeFromTs[number];
    //      = "A" | "B" | "C"
    

    所以也许您只需要在您的 ts 配置文件中添加 type AB = "A" | "B"。 :)

    【讨论】:

      【解决方案3】:

      我只是通过将as any 添加到 config.a_config 来解决它,如下所示,它可能不是最好的解决方案。

      export default function myFunc(props: myInterface)
          const [a] = useState((config.a_config as any)[props.a].map((a) => a))
      

      【讨论】:

        猜你喜欢
        • 2017-02-03
        • 2018-12-17
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 2018-10-19
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多