Búsqueda de sitios web

typescript - 'string' solo se refiere a un tipo, pero se está usando como un valor aquí


Nuevo en TypeScript. Estoy intentando establecer el estado, pero estoy recibiendo este error.

Error: 'string' solo se refiere a un tipo, pero se está usando como un valor aquí.

const state = reactive({
    user: {
        uid: "",
        provider: string[],
    }
});

const user = auth.currentUser;
if (user != null) {
    state.user.uid = user.uid || "";
    user.providerData.forEach(function(profile) {
        state.user.provider.push({
            providerId: profile.providerId,
            uid: profile.uid,
        })
    });
}

Respuesta #1

Basado solo en esta declaración:

const state = reactive({
    user: {
        uid: "",
        provider: string[],
    }
});

Lo has escrito con la intención de darle a la propiedad provider un tipo de string[], pero en esta declaración está intentando establecer el valor (no el tipo) de la variable y, como string[] no es un valor, se genera el error. Para establecer el valor de provider a un arreglo que tenga un tipo de string[], usarías:

const state = reactive({
    user: {
        // initialize as "", type is automatically set to string
        uid: "",

        // create array and override its type to an array of strings
        provider: [] as string[], 
    }
});

Sin embargo, cuando vemos cómo estás usando esta variable state:

const user = auth.currentUser;
if (user != null) {
    state.user.uid = user.uid || "";
    user.providerData.forEach(function(profile) {
        state.user.provider.push({  // <-- this bit here is important
            providerId: profile.providerId,
            uid: profile.uid,
        })
    });
}

En estas líneas estás agregando un objeto de tipo { providerId: string, uid: string } a tu array state.user.provider. Esto significa que tu primer fragmento de código en realidad necesita ser:

const state = reactive({
    user: {
        // initialize as "", the type is automatically set to string
        uid: "", 

        // create empty array and override its type to an array of { providerId: string, uid: string } objects
        provider: [] as ({ providerId: string, uid: string })[], 
    }
});

También puedes hacer uso de una interfaz para nombrar esta forma de objeto:

interface ProviderData {
  providerId: string;
  uid: string;
}
// you could also use this similar syntax:
// type ProviderData = {
//   providerId: string;
//   uid: string;
// }

const state = reactive({
    user: {
        // initialize as "", the type is automatically set to string
        uid: "", 

        // create empty array and override its type to an array of ProviderData objects
        provider: [] as ProviderData[], 
    }
});

Artículos relacionados