I am new to Typescript,encountered a problem define
loadAnimation(params: AnimationConfigWithPath | AnimationConfigWithData): AnimationItem;
export type AnimationConfigWithPath = AnimationConfig & {
path?: string;
}
export type AnimationConfigWithData = AnimationConfig & {
animationData?: any;
}
export type AnimationConfig<T extends 'svg' | 'canvas' | 'html' = 'svg'> = {
container: Element;
renderer?: T;
}
my code
lottie.loadAnimation({
container: document.getElementById("test1")!,
renderer: 'canvas', // Error: Type '"canvas"' is not assignable to type '"svg" | undefined'.
loop: true,
autoplay: true,
path: 'data.json'
})
Error: Type '"canvas"' is not assignable to type '"svg" | undefined'. I wonder how to write? thanks
CodePudding user response:
The declaration
export type AnimationConfigWithPath = AnimationConfig & {
path?: string;
}
does not pass a type parameter to AnimationConfig, which means the default value is used. So renderer will always be of type 'svg'.
You can pass the generic parameter down to get what you are looking for.
function loadAnimation<T>(params: AnimationConfigWithPath<T> | AnimationConfigWithData<T>): AnimationItem { ... }
export type AnimationConfigWithPath<T extends 'svg' | 'canvas' | 'html'> = AnimationConfig<T> & {
path?: string;
}
export type AnimationConfigWithData<T extends 'svg' | 'canvas' | 'html'> = AnimationConfig<T> & {
animationData?: any;
}
export type AnimationConfig<T extends 'svg' | 'canvas' | 'html' = 'svg'> = {
container: Element;
renderer?: T;
}
CodePudding user response:
What is this generic for? It seems pointless:
export type AnimationConfig<T extends 'svg' | 'canvas' | 'html' = 'svg'> = {
Removing it would solve the problem:
export type AnimationConfig = {
container: Element;
renderer?: "svg" | "canvas" | "html";
}
If you were using it because it has a "default value", well, types don't have a default value. They are just describing structure, not behaviour.
