V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sakuraSou
V2EX  ›  TypeScript

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

  •  
  •   sakuraSou · 240 天前 · 665 次点击
    这是一个创建于 240 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```
    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 条回复    2023-09-05 16:01:01 +08:00
    GentleFifth
        1
    GentleFifth  
       240 天前 via Android
    可以用 union type
    lsy99
        2
    lsy99  
       236 天前
    楼上+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" };
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1152 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:20 · PVG 02:20 · LAX 11:20 · JFK 14:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.