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
?
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With