Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript definitions for Animated.View's style prop

I have component whose Props interface extends ViewProps from React Native, i.e:

export interface Props extends ViewProps {
  // Custom props
}

Naturally, this extends the style prop. There is one caveat, I am using Animated.View and have style like this:

style={{
  opacity: animationCharacter.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 1]
  }),
  transform: [
    {
      scale: animationCharacter.interpolate({
        inputRange: [0, 1],
        outputRange: [1.2, 1]
      })
    }
  ]
}}

I think the interpolate call is incompatible with style typings from ViewProps, but there is no AnimatedViewProps I can extend.

Is there a solution here or will I have to set style: any?

like image 571
Ilja Avatar asked Jul 25 '18 14:07

Ilja


2 Answers

Starting from @types/react-native v0.61.9, you can use Animated.AnimatedProps:

For exemple for the style prop:

interface Props {
  style?: Animated.AnimatedProps<StyleProp<ViewStyle>>,
}

Or to get all props:

export interface Props extends Animated.AnimatedProps<ViewProps> {
  // Custom props
}
like image 51
Amaury Liet Avatar answered Nov 20 '22 16:11

Amaury Liet


I've made 'kind of' type that converts any view styles into animatable styles.

type MaybeAnimated<T> = T | Animated.Value;
type AnimatedScalar = string | number;

type AnimatedStyles<T> = {
  [Key in keyof T]: T[Key] extends AnimatedScalar
    ? MaybeAnimated<T[Key]>
    : T[Key] extends Array<infer U>
    ? Array<AnimatedStyles<U>>
    : AnimatedStyles<T[Key]>
};

type ViewAnimatedStyles = AnimatedStyles<ViewStyle>;

const test: ViewAnimatedStyles = {
  transform: [
    {
      rotateY: new Animated.Value(2),
    }
  ]
}

You get auto-suggestions and animated values work.

Limitation: Animated.Value definition under the hood is just empty class so technically, everything will match it. So you'll be able to assign an incorrect value to it (eg plain string instead of number)

Read more about infered and conditional types: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

like image 10
Adam Pietrasiak Avatar answered Nov 20 '22 15:11

Adam Pietrasiak