Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda