HammerMax
HammerMax

Reputation: 13

<Typescript> function parameter has generics. how to pass?

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

Upvotes: 1

Views: 181

Answers (1)

super
super

Reputation: 12928

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;
}

Upvotes: 1

Related Questions