简体   繁体   中英

<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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM