![](/img/trans.png)
[英]Typescript generics. Can't pass instance of B to a argument a: T where T extends B. Why?
[英]<Typescript> function parameter has generics. how to pass?
我是 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;
}
我的代碼
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'
})
錯誤:類型“canvas”不可分配給類型“svg” | 不明確的'。 請問怎么寫? 謝謝
聲明書
export type AnimationConfigWithPath = AnimationConfig & {
path?: string;
}
沒有將類型參數傳遞給AnimationConfig
,這意味着使用默認值。 所以renderer
將始終是'svg'
類型。
您可以向下傳遞通用參數以獲取您要查找的內容。
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;
}
這個泛型有什么用? 這似乎毫無意義:
export type AnimationConfig<T extends 'svg' | 'canvas' | 'html' = 'svg'> = {
刪除它可以解決問題:
export type AnimationConfig = {
container: Element;
renderer?: "svg" | "canvas" | "html";
}
如果你使用它是因為它有一個“默認值”,那么,類型沒有默認值。 它們只是描述結構,而不是行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.