V
V
Vika Marmeladka2022-03-10 18:18:09
typescript
Vika Marmeladka, 2022-03-10 18:18:09

How to conditionally add a property in TypeScript?

You need to add to the interface:

export interface ModalProps extends CuiModalProps {
    children: ReactElement | ReactElement[]
    setterClosePopup: Dispatch<SetStateAction<boolean>>
    namePopup?: string
    isOpen?: boolean
    withBorder?: boolean
    view?: 'labeled'
    className?: string
}


a label property with a value of string provided that the view property is set to 'labeled', otherwise the label should be set to never

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-03-10
@Aetae

Need more clarity. What else happens viewbesides labled?
This cannot be done through interfaces - it is possible through union types, but there must be a discriminator field that is different for each case.
If there is no such field, a specific type cannot be made, however, judging by the prefix Props, we can assume that these are some props of some React component, then this can be achieved using overloading :

export interface ModalProps extends CuiModalProps {
    children: ReactElement | ReactElement[]
    setterClosePopup: Dispatch<SetStateAction<boolean>>
    namePopup?: string
    isOpen?: boolean
    withBorder?: boolean
    className?: string
}
export interface ModalPropsLabled extends ModalProps {
    view: 'labeled'
    label: string
}

export const Component: ((pros: ModalProps) => ReactNode) & ((pros: ModalPropsLabled) => ReactNode) = (pros: ModalProps | ModalPropsLabled) => { ... }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question