Reputation: 31
Here I set the function toBase64()
export function toBase64(file:File) {
return new Promise((resolve,reject)=>{
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload=()=> resolve(reader.result);
reader.onerror=(error) =>reject(error);
})
it shows that the type of reader.result
is
string | ArrayBuffer | null
, however, when I need to use the response.
export class InputImgComponent implements OnInit {
constructor() { }
imageBase64!:string;
@Output()
onImageSelected = new EventEmitter<File>();
ngOnInit(): void {
}
change(event:any){
if(event.target.files.length>0) {
const file:File= event.target.files[0];
toBase64(file).then((value)=>this.imageBase64=value );
}
it said the result type is unknown
, and I set imageBase64
to string, Type 'unknown' is not assignable to type 'string'
.
That's really weird, how can I solve this problem, I only need the string result.
Upvotes: 3
Views: 9877
Reputation: 771
You haven't specified the type of Promise
returned by your function, so it defaults to Promise<unknown>
. Promise
is a generic type, so a promise of a string is a Promise<string>
.
You can either annotate this on the constructor of the promise, or on the return type of the function and Typescript will infer it for you.
export function toBase64(file:File) {
return new Promise<string>((resolve,reject) => {
const reader = new FileReader();
// the docs say that result should always be a string, but double-check for future-proofing
reader.onload = (ev) => typeof reader.result === "string" ? resolve(reader.result) : reject("Unexpected type received from FileReader");
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file);
})
}
Upvotes: 4
Reputation: 62213
You need to use type assertion to specify the type for value
in the lambda callback. Currently it is unknown
by default.
((value:string) => this.imageBase64=value)
Upvotes: 2