Issue
I'm working on Angular project, with typeScript. I've added FontAwesome module.
Now I want to display FontAwesome Icon from string.
`
<fa-icon class="panel-heading__icon" [icon]="['fas', iconName]"></fa-icon>
`
When i put directly a good value of IconName, like that: `
public iconName: IconName = 'coffee';
`
It works.
But, I need to pass a variable string and convert it to IconName. `
this.iconName = this._model?.icon
` I get : "Type 'string' is not assignable to type 'IconName'.ts(2322)"
How fix it ?
Solution
Basically the typescript type checker is complaining because you are trying to use a string instead of an IconName. The IconName type from font-awesome is a type that allows different string literals but not any arbitrary string value. You have two options to fix this problem:
Option 1:
Use the proper type for the icon attribute on the model type.
So for example if the type of the _model
attribute is an interface this can look like this:
interface Model {
...
icon: IconName
}
Option 2: If you can't change the model type you can tell the typescript compiler that you are sure that this icon property has the IconName type by using a type assertion:
this.iconName = this._model?.icon as IconName.
Be aware that there is no runtime check that the icon attribute really hold a valid IconName.
Answered By - Jakob Em
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.