Angular 12/TypeScript类型错误求助:any类型无法赋值给never类型
Hey there! Let's break down and fix this TypeScript error you're hitting in your Angular 12 project.
The Root Cause
This error pops up because TypeScript has inferred your recordedChunks array as type never[]—when you initialize an empty array without explicitly defining its type, TypeScript defaults to never[] if it can't guess a more specific type. When you try to push event.data (typed as any) into this array, TypeScript throws an error because never is a type that can't accept any value at all.
Step-by-Step Solution
Explicitly type your
recordedChunksarray
Since thedataproperty from the MediaRecorder'sondataavailableevent is aBlob, you should declare your array to holdBlobvalues explicitly:// Inside your component class recordedChunks: Blob[] = [];Use the native event type instead of a custom
{ data: any; }type
TypeScript provides a built-inBlobEventtype for this exact DOM event scenario, which correctly typesevent.dataasBlob—no need for a vague custom type:this.recorder.ondataavailable = (event: BlobEvent) => { this.recordedChunks.push(event.data); };
Why This Works
By specifying Blob[] for recordedChunks, you tell TypeScript exactly what kind of values the array should store. Pairing this with the native BlobEvent type ensures that event.data perfectly matches the array's expected type, eliminating the type mismatch error entirely.
Quick (But Not Ideal) Workaround
If you need a temporary fix (though I strongly recommend the typed approach above), you can explicitly type recordedChunks as any[] to bypass TypeScript's type checking:
recordedChunks: any[] = [];
Note that this loses the type safety benefits that make TypeScript useful, so it's better to stick with the proper typed solution long-term.
内容的提问来源于stack exchange,提问作者deszok

