TypeScript Typ Arv: Hur man tilldelar en variabel med föräldratyp till en variabel med barn typ
Jag har skapat två typer
export class GenericType {
public id: string;
public property: string;
public name: string;
}
export class SpecificType extends GenericType {
public value: string;
}
Nu har jag två variabler A: GenericType och B: SpecificType, nu vill jag tilldela alla värden från A till B, och dessutom vill jag tilldela value till B. Hur ska jag uppnå detta, jag vill inte loopa genom alla egenskaper i A och manuellt tilldela dem till alla egenskaper i B.
let varA: GenericType = {
id: '123',
property: 'exmple',
name: 'example variable',
};
let varB: SpecificType = new SpecificType();
varB = varA; <----- not allowing to assign.
varB.value = 'new value';
Svar #1
Du kan inte göra detta:
let varA: GenericType = {
id: '123',
property: 'exmple',
name: 'example variable',
};
let varB: SpecificType = new SpecificType();
varB = varA; <----- not allowing to assign.
varB.value = 'new value';
Men du kan göra detta:
let varA: GenericType = {
id: '123',
property: 'exmple',
name: 'example variable',
};
let varB: SpecificType = new SpecificType();
// Difference here:
varB = { ...varA, value: 'new value' }
Du kan inte tilldela varA till varB eftersom varA inte har value, men du kan tilldela allt tillsammans med hjälp av spread-operatorn.
Svar #2
Du får inte tilldela det eftersom egenskapen value inte finns i klassen GenericType, för att kringgå detta kan du göra en typförsäkran till SpecificType:
let varB: SpecificType = new SpecificType();
varB = varA as SpecificType; // Allowed to assign now.
varB.value = 'new value';
