Object is possibly ‘undefined’ when apply for number

I’m trying to make custom view component base on device size, but typescript complain about number, it said Object is possibly 'undefined', here is the code

export interface ViewContainerProps {
  style?: ViewStyle | ViewStyle[];
  children?: React.ReactNode;
  percentWidth?: number;
  percentHeight?: number;
}
export const ViewContainer = (props: ViewContainerProps) => {
  const {style, children, percentHeight,percentWidth} = props;
  return (
    <View style={[style, {height: onePercentHeight * percentHeight}]}> // no, this number is undefined!?
      {children}
    </View>
  );
};

What happen, how to fix this, thank you guys a lots

Answer

You can also try to give a default fallback to your variable or use a non-null assertion operator

Default value: -1 can be replaced by your default value

variable || -1

non-null assertion operator (!) at the end of variable

(By adding the exclamation mark (!) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null)

variable!