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

253 天前
 sakuraSou
```
interface Layout {hasPadding?:boolean;padding?:string}
```
大佬们,问一下 ts 类型相关的问题:

`interface Layout = {hasPadding?:boolean;padding?:string}`
改成
当 Layout['hasPadding'] 的类型为 true 时,layout['padding'] 的类型为 string
当 Layout['hasPadding'] 的类型为 false 时,Layout 类型里面没有 padding 这个属性呀
707 次点击
所在节点    TypeScript
2 条回复
GentleFifth
253 天前
可以用 union type
lsy99
250 天前
楼上+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" };

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/970211

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX