how to resolve “typescript is not assignable to parameter of type …”

This article shows you how to overcome incompatible type when you are coding in Typescript for Angular.

Sometimes, you are certain that you need to get or set a property into another property but typescript rules don’t allow different type assignment or access.

Although, in most cases , this is consider bad practice, some cases, you might already override some of the properties but the typescript compiler rule not updated and understand this.

To overcome this, here are few ways
1) Assigning to different type via Explicit casting


//example
const oldProperty: number = 11;
let newProperty: string = `${oldProperty}`; // or  newProperty:string= '' +oldProperty

 or

const oldProperty1: number = 11;
let newProperty1: any = oldProperty; 

2) Accessing certain property not defined in type


//before:typescript compiler complain itemName not in someProperty
 someProperty.itemName 

//after:access it via its property 
 someProperty['itemName']

//before:example typescript complains here
 window.msCrypto 

//after:so do this instead
window['msCrypto']
 

3) Wrap in another list or object


let newObjectItem:any ={};
newObjectItem['yourFixedTypeItem'] = yourFixedTypeItemObject ;

or

let newList = [];
newList.push(newObjectItem);

4) Raised an issue in github for typescript compiler or override/extend the default definitions


//definition extended
class SomeRigidTypeExtended  extends SomeRigidType{
    newProperty:string;
}

//before:typescript compiler will complain
item: SomeRigidType = new SomeRigidType(); 
item.newProperty = 'abc';

//after:typescript compiler will NOT complain
newItem: SomeRigidTypeExtended = new SomeRigidTypeExtended (); 
newItem.newProperty = 'abc';

That’s it in most cases. Hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *