typescript not throwing error when passed an object that should throw

Viewed 169

I have some code that I expect to throw an error that isn't in typescript and I'm not sure why. I have the following code in a react native project:

  const styles = {
    flexGrow: 1,
    width: '100%',
  } as const

  return <View style={styles} />

This is all well and good. However, if I add an invalid style to styles:

  const styles = {
    flexGrow: 1,
    width: '100%',
    invalidStyle: 'bla'
  } as const

  return <View style={styles} />

Typescript does not throw an error.

This works (throws an error) if I put the styles directly on the style prop on View:

  return <View style={{
    flexGrow: 1,
    width: '100%',
    invalidStyle: 'bla'
  }} />

I correctly get Object literal may only specify known properties, and 'randomProps' does not exist in type 'ViewStyle | RecursiveArray<Falsy | ViewStyle | RegisteredStyle<ViewStyle>>'.

Is there anything I can do to make sure I get this error in the non-direct assignment of styles?

2 Answers

Please try explicit specification of the style type.

const styles: CSSProperties = {
    flexGrow: 1,
    width: '100%',
    invalidStyle: 'bla'
  } as const

Then typescript will understand what to validate during initialization of the variable.

It's happening because the type of your styles const is a simple object, not a Stylesheet object, so it doesn't know what style values are appropriate. To fix that, define your styles like this:

const styles = StyleSheet.create({
     viewStyle: {
         flexGrow: 1,
         width: "100%",
         invalidStyle: "bla",
     },
});

return <View style={styles.viewStyle} />
Related