Home > Software engineering >  How to use a boolean to control other properties as required in typescript?
How to use a boolean to control other properties as required in typescript?

Time:03-07

Is there any way to make properties inside PaginationProps required when enablePagination is true?

Is this possible?

interface PaginationProps {
  total?: number;
  offset?: number;
  limit?: number;
}

interface Props<T> extends PaginationProps {
  data: T;
  enablePagination: boolean;
}

CodePudding user response:

I wish I could answer this. Maybe I'll attempt it (but not right this moment).

I think you need to use the Required utility type in conjunction with conditional types.

EDIT Thanks to @Federkun - here's the solution:

interface PaginationProps {
  total?: number
  offset?: number
  limit?: number
}
type OptionalPaginationProps = ({ enabledPagination: false } & PaginationProps) | ({ enabledPagination: true } & Required<PaginationProps>)
type Props<T> = OptionalPaginationProps & { data: T; } 

const propsNoPagination: Props<string> = {
  data: 'hello',
  enabledPagination: false
}
const propsWithPagination: Props<string> = {
  data: 'hello',
  enabledPagination: true,
  total: 1,
  offset: 2,
  limit:3
}
  • Related