Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Type 'unknown' is not assignable to type 'string'

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
    })
}
over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!