Typescript definitions for Animated.View's style prop
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
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
}