简体   繁体   English

<typescript> function参数有generics,怎么传?</typescript>

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

I am new to Typescript,encountered a problem define我是 Typescript 的新手,遇到了一个问题 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" |错误:类型“canvas”不可分配给类型“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.没有将类型参数传递给AnimationConfig ,这意味着使用默认值。 So renderer will always be of type 'svg' .所以renderer将始终是'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.它们只是描述结构,而不是行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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