I’m working on a SvelteKit project where I’m trying to create a console-like interface. Each line in the console can either be a prompt component for user input or a log component for displaying messages.
type def:
export type Prompt = [typeof PromptComponent, {
onTextInput: (arg0: Event) => void;
onKeyDown: (arg0: KeyboardEvent) => void;
setInputRef: (ref: HTMLTextAreaElement | null) => void;
}];
export type Log = [typeof LogComponent, {
str: string;
}];
export type ConsoleLine = Prompt | Log;
I create the components like this:
const newPrompt = () => {
const newComponent: Prompt = [
PromptComponent,
{
onTextInput: onTextInput,
onKeyDown: onKeyDown,
setInputRef: setInputRef
}
];
lines = [...lines, newComponent];
};
const newLog = (str: string) => {
if (!str.length) return;
const newComponent: Log = [
LogComponent,
{
str: str
}
];
lines = [...lines, newComponent];
};
rendering:
{#each lines as line}
<svelte:component this={line[0]} {...line[1]} />
{/each}
I’m getting the following TypeScript error:
Type ‘{ onTextInput: (arg0: Event) => void; onKeyDown: (arg0:
KeyboardEvent) => void; setInputRef: (ref: HTMLTextAreaElement | null)
=> void; } | { …; }’ is not assignable to type ‘({ onTextInput: any; onKeyDown: any; setInputRef: any; } & { str: any; }) | undefined’.
TypeScript doesn’t seem to understand that an element can’t be of type Prompt and Log at the same time. How can I resolve this error in a clean and production-ready manner ?