Given the following interface, what would be a valid assignable value?
interface A {
x: number,
y: never
}
What I expected was that const a: A = { x: 1 }
would work, but it errors saying field y
is required. As soon as I put y
in there, it says that the value is not assignable to never
.
My actual use case is something like this:
interface Context<T extends MyRequest> {
id: string;
token: T extends AuthenticateRequest ? string : never;
}
interface AuthenticatedRequest extends MyRequest { ... }
Here I am unable to create a value for Context<MyRequest>
since it says token
is missing.
A workaround I currently have is:
type Context<T extends MyRequest> = {
id: string;
} & (T extends AuthenticatedRequest ? {
token: string;
} : {})
but for obvious reasons, this looks ugly...
Any ideas how I do this correctly ?
Based on points mentioned by @Titian Cernicova-Dragomir and @Maciej Sikora, the workaround is the right way to go for the type definition I need. An
interface
cannot have a field of typenever
, since it can't be assigned a valid value, thereby making the interface useless.Here's what I finally used for my code: