1

How would I write conditional boolean type for this?

i.e

export interface Props {
  editable: boolean;
  position: { editable: true } ? Sheets.Matrix : never;
  value: string;
  classNames?: string;
  textType?: "bold" | "editing" | "normal";
  onChange?: (val: Sheets.SaveData) => void;
}

I use props like this

const SheetsCell: React.FC<MainProps> = ({
  editable,
  value,
  textType = "normal",
  classNames = "",
  position,
  ...

Here if something is editable, I want the type of position to be Sheets.Matrix else, position isn't required.

2 Answers 2

1

One way to do it is using an interface and the intersection operator(&).

You can use an intersection type, which combines multiple types into one.

interface Props {
  value: string;
  classNames?: string;
  textType?: "bold" | "editing" | "normal";
  onChange?: (val: number) => void;
}

type MainProps = Props & {
  editable: true;
  position: number; 
} | Props & {
  editable: false;
  position?: number; 
}; 

The above type MainProps forces editable to be true in one case and false in another. If editable is true, then position property exists and if it is false, position property exists but it is not required.

unions is used above, to generate a type which can be one of the two values. MainProps can be one of the two types (both being intersection with Props type).

Here is the playground link

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, Small correction, I think for Props & { editable: false; } you need to add position?: undefined else typescript throws error
Ok I missed that part. position is allowed but it can be optional is it?
Updated the question: So, Yeah, I de-structure (as in now question).
You can just do Props & ({ editable: false } | { editable: true, position: number })
thanks @Nullndr, you can edit the answer if you feel like. Or i can add it. This is a good tip.
1

You could use type aliases instead of an interface e.g.

type Props = { 
  editable: true;
  position: Sheets.Matrix;
} | { 
  editable: false;
};

const testFalse: Props = { // position not required
  editable: false
}
    
const testTrue: Props = { // position mandatory
  editable: true,
  position: MatrixEnum
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.