I searched a lot but couldn't find. My Codes as below.
I created one alertify Service but I get the following error: "Type 'undefined' cannot be used as an index type. Partial<Class> undefined ?"
I don't understand why the code is detecting my index type as 'undefined'.
import { Injectable } from '@angular/core';
declare let alertify: any;
@Injectable({
providedIn: 'root'
})
export class AlertifyService {
constructor() { }
message(message: string, options: Partial<AlertifyOptions>) {
alertify.set('notifier', 'position', options.position);
alertify.set('notifier', 'delay', options.delay);
alertify[options.messageType](message);
}
}
export class AlertifyOptions {
messageType: AlertifyMessageType = AlertifyMessageType.Success;
position: AlertifyPositions = AlertifyPositions.BottomRightCenter;
delay: number = 3;
dismissOthers: boolean = false;
}
export enum AlertifyMessageType {
Success = "success",
Warning = "warning",
Message = "message",
Error = "error",
Notifier = "notifier"
}
export enum AlertifyPositions {
TopRight = "top-right",
TopCenter = "top-center",
Topleft = "top-left",
BottomRight = "bottom-right",
BottomRightCenter = "bottom-center",
BottomRightBottom = "bottom-right"
}
tl;dr make sure you null check properties from a
Partialtype before trying to use themWhen you use the
Partialtype in TypeScript, you effectively take an existing type and mark each property as optional. An optional type in TypeScript is for most intents and purposes equivalent to the key being capable of beingundefined.For example:
Because all keys are optional, in essence that means none of them are mandatory. A completely valid assignment of
PartialSomeObjectis as follows:Back to your example, you have the following:
In this case you are passing in your
optionsproperty asPartial<AlertifyOptions>which means (as stated above) that this value ofoptionsmay not contain any of the keys which you are using within the block. So in order for TypeScript to allow you to use anyoptionsinformation downstream, you need to prove that the key you are interested is actually presentAs you are trying to use
options.messageTypeas an index on thealertifyclass/object, TypeScript is saying that if this value were to beundefined, it would not be possible to be used as an index. i.e.alertify[undefined]is invalid syntax.You need to make sure that
options.messageTypeis notundefinedbefore using it. This can be achieved by simply null checking:Note: I am assuming that the type of
options.messageTypeis a union of possible keys on thealertifyclass/object. If this is not the case, the operation would be invalid with or without the null check above