1. 如何在TypeScript中根据对象的结构动态决定属性的必填性?-灵析社区

疯狂的搬运工

type A = { b: { c?: string; }; a: { c: string; }; }; interface AddDisplayItem { data: A[T]; } 我希望`data`是否必传由`A[T]`是否有必传属性决定。如何做呢?

阅读量:12

点赞量:0

问AI
type A = { b: { c?: string; }; a: { c: string; }; }; type AllOptional = { [K in keyof T]-?: {} extends Pick ? never : K }[keyof T] extends never ? true : false; type AddDisplayItem = AllOptional extends true ? { data?: A[T] } : { data: A[T] }; const item1: AddDisplayItem = { data: { c: 'Hello' } }; // 'data' is required const item2: AddDisplayItem = {}; // 'data' is optional