I'm quite new to typescript, I'd like to know how to make this function.
I have something that closely resembles the following union type structure setup. Unfortunately it doesn't quite work as I'd expect. The failType
below, contains properties of both NodeA
and NodeB
types.
I would expect both captureContentId
and nodes
to give me an error or al least have to compiler tell me that it can't figure out which of the four types it is supposed to be. Right now this just silently works.
Did I miss some syntax somewhere or is what I want to achieve just not possible? You can check out the code in the typescript playground here.
type Capture = {
readonly [k: string | number]: { readonly contentId?: number; readonly nodes?: Array<IncludeNode | NodeA | NodeB> };
}
interface NodeA {
readonly contentId?: number;
readonly captures?: Capture;
}
interface NodeB {
readonly contentId?: number;
readonly captureContentId?: number;
readonly beginCaptures?: Capture;
readonly endCaptures?: Capture;
readonly nodes?: Array<IncludeNode | NodeA | NodeB>;
}
interface IncludeNode {
readonly include: UnionType;
}
interface NodeArray {
readonly nodes: Array<IncludeNode | NodeA | NodeB>;
}
type UnionType = IncludeNode | NodeA | NodeB | NodeArray;
const aType: UnionType = {
captures: { 1: { contentId: 5000 } },
};
const failType: UnionType = {
contentId: 4003,
captures: {
1: { contentId: 3009 },
},
// These should not be allowed, yet they are?
captureContentId: 4099,
nodes: [{ include: aType }],
};