Reputation: 3179
Possibly an odd question, but I'm curious if it's possible to make an interface where one property or the other is required.
So, for example...
interface Message {
text: string;
attachment: Attachment;
timestamp?: number;
// ...etc
}
interface Attachment {...}
In the above case, I'd like to make sure that either text
or attachment
exists.
This is how I'm doing it right now. Thought it was a bit verbose (typing botkit for slack).
interface Message {
type?: string;
channel?: string;
user?: string;
text?: string;
attachments?: Slack.Attachment[];
ts?: string;
team?: string;
event?: string;
match?: [string, {index: number}, {input: string}];
}
interface AttachmentMessageNoContext extends Message {
channel: string;
attachments: Slack.Attachment[];
}
interface TextMessageNoContext extends Message {
channel: string;
text: string;
}
Upvotes: 270
Views: 196462
Reputation: 105
You can also so it this way.
abstract class BaseMessage {
timestamp?: number;
/* more general properties here */
constructor(timestamp?: number) {
this.timestamp = timestamp;
/* etc. for other general properties */
}
}
interface IMessageWithText extends BaseMessage {
text: string;
attachment?: never;
}
interface IMessageWithAttachment extends BaseMessage {
text?: never;
attachment: string;
}
type Message = IMessageWithText | IMessageWithAttachment;
Upvotes: 7
Reputation: 553
I have further compressed the solution from @Voskanyan David to get to this solution which I personally find very neat:
You still have to define Only<> and Either<> once somewhere
type Only<T, U> = {
[P in keyof T]: T[P];
} & {
[P in keyof U]?: never;
};
type Either<T, U> = Only<T, U> | Only<U, T>
Afterwards, it becomes possible to define it without any intermediate interfaces/types as one thing:
type Message = {
type?: string;
channel?: string;
user?: string;
// ...etc
} & Either<{message: string}, {attachment: Attachment}>
Upvotes: 13
Reputation: 2732
Here is a very simple utility type that I use for creating a new type that allows one of multiple interfaces/types called InterfacesUnion
:
export type InterfacesUnion<Interfaces> = BuildUniqueInterfaces<UnionToIntersection<Interfaces>, Interfaces>;
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
export type BuildUniqueInterfaces<CompleteInterface, Interfaces> = Interfaces extends object
? AssignNever<CompleteInterface, Interfaces>
: never;
type AssignNever<T, K> = K & {[B in Exclude<keyof T, keyof K>]?: never};
It can be used as follows:
type NewType = InterfacesUnion<AttachmentMessageNoContext | TextMessageNoContext>
It operates by accepting a union of interfaces/types, building up a single interface that contains all of their properties and returning the same union of interfaces/types with each one containing additional properties that other interfaces had and they didn't with those properties being set to optional never ([propertyName]?: never).
Playground with examples/explanation
Upvotes: 1
Reputation: 659
Using XOR described here: https://stackoverflow.com/a/53229567/8954109
// Create a type that requires properties `a` and `z`, and one of `b` or `c`
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
interface Az {
a: number;
z: number;
}
interface B {
b: number;
}
interface C {
c: number;
}
type XorBC = XOR<B, C>;
type AndAzXorBC = Az & XorBC;
type MyData = AndAzXorBC;
const ok1: MyData = { a: 0, z: 1, b: 2 };
const ok2: MyData = { a: 0, z: 1, c: 2 };
const badBothBC: MyData = {
a: 0, z: 1,
b: 2,
c: 3
};
const badNoBC: MyData = { a: 0, z: 1 };
const badNoZ: MyData = { a: 0, b: 2 };
Produces these errors for invalid types:
src/App.tsx:30:7 - error TS2322: Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'AndAzXorBC'.
Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'Az & Without<C, B> & B'.
Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'Without<C, B>'.
Types of property 'c' are incompatible.
Type 'number' is not assignable to type 'undefined'.
30 const badBothBC: MyData = {
src/App.tsx:35:7 - error TS2322: Type '{ a: number; z: number; }' is not assignable to type 'AndAzXorBC'.
Type '{ a: number; z: number; }' is not assignable to type 'Az & Without<C, B> & B'.
Property 'b' is missing in type '{ a: number; z: number; }' but required in type 'B'.
35 const badNoBC: MyData = { a: 0, z: 1 };
~~~~~~~
src/App.tsx:17:3
17 b: number;
~
'b' is declared here.
src/App.tsx:36:7 - error TS2322: Type '{ a: number; b: number; }' is not assignable to type 'AndAzXorBC'.
Type '{ a: number; b: number; }' is not assignable to type 'Az & Without<C, B> & B'.
Property 'z' is missing in type '{ a: number; b: number; }' but required in type 'Az'.
36 const badNoZ: MyData = { a: 0, b: 2 };
~~~~~~
src/App.tsx:13:3
13 z: number;
~
'z' is declared here.
Upvotes: 2
Reputation: 2854
Simple 'need one of two' example:
type Props =
| { factor: Factor; ratings?: never }
| { ratings: Rating[]; factor?: never }
Upvotes: 12
Reputation: 685
Nobody has mentioned it so far, but I think that whoever stumbles upon this page may also consider using discriminated unions. If I properly understood the intensions of the OP's code then it might be transformed like this.
interface Attachment {}
interface MessageBase {
type?: string;
user?: string;
ts?: string;
team?: string;
event?: string;
match?: [string, {index: number}, {input: string}];
}
interface AttachmentMessageNoContext extends MessageBase {
kind: 'withAttachments',
channel: string;
attachments: Attachment[];
}
interface TextMessageNoContext extends MessageBase {
kind: 'justText',
channel: string;
text: string;
}
type Message = TextMessageNoContext | AttachmentMessageNoContext
const textMessage: Message = {
kind: 'justText',
channel: 'foo',
text: "whats up???"
}
const messageWithAttachment: Message = {
kind: 'withAttachments',
channel: 'foo',
attachments: []
}
Now Message
interface requires either attachments
or text
depending on the kind
property.
Upvotes: 4
Reputation: 211
I've stumbled upon this thread when looking for an answer for my case (either propA, propB or none of them). Answer by Ryan Fujiwara almost made it but I've lost some checks by that.
My solution:
interface Base {
baseProp: string;
}
interface ComponentWithPropA extends Base {
propA: string;
propB?: never;
}
interface ComponentWithPropB extends Base {
propB: string;
propA?: never;
}
interface ComponentWithoutProps extends Base {
propA?: never;
propB?: never;
}
type ComponentProps = ComponentWithPropA | ComponentWithPropB | ComponentWithoutProps;
This solution keeps all checks as they should be. Perhaps someone will find this useful :)
Upvotes: 14
Reputation: 1177
You can go deeper with @robstarbuck solution creating the following types:
type Only<T, U> = {
[P in keyof T]: T[P];
} & {
[P in keyof U]?: never;
};
type Either<T, U> = Only<T, U> | Only<U, T>;
And then Message
type would look like this
interface MessageBasics {
timestamp?: number;
/* more general properties here */
}
interface MessageWithText extends MessageBasics {
text: string;
}
interface MessageWithAttachment extends MessageBasics {
attachment: string;
}
type Message = Either<MessageWithText, MessageWithAttachment>;
With this solution you can easily add more fields in MessageWithText
or MessageWithAttachment
types without excluding it in another.
Upvotes: 92
Reputation: 8091
If you're truly after "one property or the other" and not both you can use never
in the extending type:
interface MessageBasics {
timestamp?: number;
/* more general properties here */
}
interface MessageWithText extends MessageBasics {
text: string;
attachment?: never;
}
interface MessageWithAttachment extends MessageBasics {
text?: never;
attachment: string;
}
type Message = MessageWithText | MessageWithAttachment;
// 👍 OK
let foo: Message = {attachment: 'a'}
// 👍 OK
let bar: Message = {text: 'b'}
// ❌ ERROR: Type '{ attachment: string; text: string; }' is not assignable to type 'Message'.
let baz: Message = {attachment: 'a', text: 'b'}
Upvotes: 319
Reputation: 49
Ok, so after while of trial and error and googling I found that the answer didn't work as expected for my use case. So in case someone else is having this same problem I thought I'd share how I got it working. My interface was such:
export interface MainProps {
prop1?: string;
prop2?: string;
prop3: string;
}
What I was looking for was a type definition that would say that we could have neither prop1 nor prop2 defined. We could have prop1 defined but not prop2. And finally have prop2 defined but not prop1. Here is what I found to be the solution.
interface MainBase {
prop3: string;
}
interface MainWithProp1 {
prop1: string;
}
interface MainWithProp2 {
prop2: string;
}
export type MainProps = MainBase | (MainBase & MainWithProp1) | (MainBase & MainWithProp2);
This worked perfect, except one caveat was that when I tried to reference either prop1 or prop2 in another file I kept getting a property does not exist TS error. Here is how I was able to get around that:
import {MainProps} from 'location/MainProps';
const namedFunction = (props: MainProps) => {
if('prop1' in props){
doSomethingWith(props.prop1);
} else if ('prop2' in props){
doSomethingWith(props.prop2);
} else {
// neither prop1 nor prop2 are defined
}
}
Just thought I'd share that, cause if I was running into that little bit of weirdness then someone else probably was too.
Upvotes: 4
Reputation: 2707
There're some cool Typescript option that you could use https://www.typescriptlang.org/docs/handbook/utility-types.html#omittk
Your question is: make an interface where either 'text' or attachment exist. You could do something like:
interface AllMessageProperties {
text: string,
attachement: string,
}
type Message = Omit<AllMessageProperties, 'text'> | Omit<AllMessageProperties, 'attachement'>;
const messageWithText : Message = {
text: 'some text'
}
const messageWithAttachement : Message = {
attachement: 'path-to/attachment'
}
const messageWithTextAndAttachement : Message = {
text: 'some text',
attachement: 'path-to/attachment'
}
// results in Typescript error
const messageWithOutTextOrAttachement : Message = {
}
Upvotes: 2
Reputation: 1775
You can create few interfaces for the required conditions and join them in a type like here:
interface SolidPart {
name: string;
surname: string;
action: 'add' | 'edit' | 'delete';
id?: number;
}
interface WithId {
action: 'edit' | 'delete';
id: number;
}
interface WithoutId {
action: 'add';
id?: number;
}
export type Entity = SolidPart & (WithId | WithoutId);
const item: Entity = { // valid
name: 'John',
surname: 'Doe',
action: 'add'
}
const item: Entity = { // not valid, id required for action === 'edit'
name: 'John',
surname: 'Doe',
action: 'edit'
}
Upvotes: 8
Reputation: 2494
Thanks @ryan-cavanaugh that put me in the right direction.
I have a similar case, but then with array types. Struggled a bit with the syntax, so I put it here for later reference:
interface BaseRule {
optionalProp?: number
}
interface RuleA extends BaseRule {
requiredPropA: string
}
interface RuleB extends BaseRule {
requiredPropB: string
}
type SpecialRules = Array<RuleA | RuleB>
// or
type SpecialRules = (RuleA | RuleB)[]
// or (in the strict linted project I'm in):
type SpecialRule = RuleA | RuleB
type SpecialRules = SpecialRule[]
Update:
Note that later on, you might still get warnings as you use the declared variable in your code. You can then use the (variable as type)
syntax.
Example:
const myRules: SpecialRules = [
{
optionalProp: 123,
requiredPropA: 'This object is of type RuleA'
},
{
requiredPropB: 'This object is of type RuleB'
}
]
myRules.map((rule) => {
if ((rule as RuleA).requiredPropA) {
// do stuff
} else {
// do other stuff
}
})
Upvotes: 9
Reputation: 220884
You can use a union type to do this:
interface MessageBasics {
timestamp?: number;
/* more general properties here */
}
interface MessageWithText extends MessageBasics {
text: string;
}
interface MessageWithAttachment extends MessageBasics {
attachment: Attachment;
}
type Message = MessageWithText | MessageWithAttachment;
If you want to allow both text and attachment, you would write
type Message = MessageWithText | MessageWithAttachment | (MessageWithText & MessageWithAttachment);
Upvotes: 161