sakuraSou

求助帖, 问下在 ts 中如何使 接口中的一个可选属性依赖接口另一个必选属性

  •  
  •   sakuraSou · Sep 1, 2023 · 1658 views
    This topic created in 983 days ago, the information mentioned may be changed or developed.
    ```
    interface Layout {hasPadding?:boolean;padding?:string}
    ```
    大佬们,问一下 ts 类型相关的问题:

    `interface Layout = {hasPadding?:boolean;padding?:string}`
    改成
    当 Layout['hasPadding'] 的类型为 true 时,layout['padding'] 的类型为 string
    当 Layout['hasPadding'] 的类型为 false 时,Layout 类型里面没有 padding 这个属性呀
    2 replies    2023-09-05 16:01:01 +08:00
    GentleFifth
        1
    GentleFifth  
       Sep 1, 2023 via Android
    可以用 union type
    lsy99
        2
    lsy99  
       Sep 5, 2023
    楼上+1 , 用 type 的联合类型
    type Layout = { hasPadding: false } | { hasPadding: true; padding: string };

    // correct
    const layout1: Layout = { hasPadding: true, padding: "12px" };
    const layout2: Layout = { hasPadding: false };

    // wrong
    //@ts-expect-error
    const layout3: Layout = { hasPadding: true };
    //@ts-expect-error
    const layout4: Layout = { hasPadding: false, padding: "12px" };
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5126 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 09:44 · PVG 17:44 · LAX 02:44 · JFK 05:44
    ♥ Do have faith in what you're doing.