Given the following:
type ActionType =
'action1' |
'action2' |
'action3';
interface Action {
type: ActionType;
value?: number | Date;
}
Is there a way in typescript to restrict the type of value
based on the value of type
?
For example, if type
equals action1
or action2
, I want the value
field to be of type number
but if type
is action3
then I want the value to be of type Date
.
It's probably not possibly but just checking..
Your best chance would probably be to use discriminated unions:
type Action = {
type: 'action1' | 'action2';
value: number;
} | {
type: 'action3';
value: Date;
}
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.