简体   繁体   中英

TS: How to handle multiple possible types on a single type?

I have an Modal Data Interface

interface ModalData {
 ...
 payload: any; // At any given time, this payload might be a string or number or boolean;
 ...
}

In the modal data payload have a possibility of different types, so for that I had created another type:

type IPayLoad = string | number | boolean;

Now when I use this types on my code I'm getting the below errors.

The problem is I don't like setting the any type to payload above. But if I set it to the type IPayLoad , I'm getting the below errors.

this.service.saveString(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'string'.

this.service.saveNumber(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'number'.

this.service.saveBool(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'boolean'.

The calling functions in the service are here below:

public saveString(res: string): void {}

public saveNumber(res: number): void {}

public saveBool(res: boolean): void {}

Assuming you have set the type of ModalData.payload to IPayLoad instead of any , you'll need to narrow down the union type like this:

if (typeof modal.payload === 'string') {
    saveString(modal.payload)
} else if (typeof modal.payload === 'number') {
    saveNumber(modal.payload)
} else if (typeof modal.payload === 'boolean') {
    saveBool(modal.payload)
}

The typeof -checks are called type guards, which you can read more about in the TypeScript documentation .

I think you can use one method that accepts IPayload or string|boolean|number type.

But if you really want to use those three functions,

You can do as the following:

this.service.saveString(`${payload}`);

this.service.saveNumber(Number(payload));

this.service.saveBoolean(Boolean(payload));

The keyword as solves the problem here.

public getLoad (payload: IPayLoad) {

  this.service.saveString(payload as string);

  this.service.saveNumber(payload as number);

  this.service.saveBoolean(payload as boolean);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM