On a personal project I am facing an issue with TypeScript conditional types. I have basic understanding of conditional types from the TypeScript docs. I would expect the setup below to work but it gives a type error.
Basicaly I am trying to define an interface for a tree node which is loaded from the disk. This means that some of the nodes may not be correctly loaded because of missing files etc. So any node implementation either contains Content or Error.
interface Content {
data: number;
}
interface Error {
code: string;
}
export interface TreeNode<T extends Content | Error> {
getValue(): T extends Content ? number : string;
}
class ValueNode<ValueType extends Content> implements TreeNode<ValueType> {
private readonly value: number;
public constructor(value: number) {
this.value = value;
}
public getValue(): number {
return this.value;
}
}
I would expect that the implementation of the getValue method would be allowed to return string since the interface is implemented with type extending Content. But I get this type error intead:
- Property
getValuein typeValueNode<ValueType>is not assignable to the same property in base typeTreeNode<ValueType>.
- Type
() => numberis not assignable to type() => ValueType extends Content ? number : string.
- Type
numberis not assignable to typeValueType extends Content ? number : string
Cleary, I am doing it the wrong way. What would be the correct way to achieve my goal?
ValueTypeis a type-parameter, why aren't you using it at all insideValueNode<...>?Erroris a built-in type, so you should give yourinterface Errora distinct name, likeinterface MyErroror so.class ValueNode implements TreeNode<Content>is what you're looking for..