I'd like to define an interface that allows you to supply content
OR content_object
but not both. You have to define one or the other. What is the simplest way to achieve this in TypeScript? I know I could say that content is string | object
, but the rest of my code benefits if I can define it as described instead.
interface IModal {
content?: string;
content_object?: object;
}
I'd like to define an interface that allows you to supply content
OR content_object
but not both. You have to define one or the other. What is the simplest way to achieve this in TypeScript? I know I could say that content is string | object
, but the rest of my code benefits if I can define it as described instead.
interface IModal {
content?: string;
content_object?: object;
}
Share
Improve this question
asked May 10, 2018 at 22:08
jas7457jas7457
1,78215 silver badges22 bronze badges
5
- Are you just wanting to know how to implement the constraints? – Robert Harvey Commented May 10, 2018 at 22:10
- Yes. What I currently have says that both are optional, but both could be present as well. I want it to only allow 1, and ensure that exactly one are set. – jas7457 Commented May 10, 2018 at 22:11
- You'll need some validation in your implementation class. AFAIK you can't enforce such constraints in the interface itself. – Robert Harvey Commented May 10, 2018 at 22:13
- You could also try this: npmjs./package/typedcontract – Robert Harvey Commented May 10, 2018 at 22:15
- Hmmm interesting package, but a bit overkill for this one scenario. Thanks though. – jas7457 Commented May 10, 2018 at 22:18
1 Answer
Reset to default 9type IModal = { content: string; content_object?: undefined } |
{ content_object: object; content?: undefined }
This answer contains only code and is therefore bad according to automated systems.