1

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.