Is there a way to perform type checking on the value assigned to a variable without changing or widening its type?
For instance,
const a = {foo: "hi"} as const; // typeof = {foo: "hi"}
type THasFoo = {foo: string};
const b: THasFoo = {foo: "hi"} as const; // typeof = THasFoo
I want to verify that whatever is assigned to variable a
contains the property foo
, while still retaining the original type information.
Please note: I am specifically interested in the kind of verification achieved through direct assignment. For example,
const a = {foo: "hi", bar: "world"} as const;
type THasFoo = {foo: string};
const b: THasFoo = a;
This will pass. However,
type THasFoo = {foo: string};
const b: THasFoo = {foo: "hi", bar: "world"} as const;
Will not pass. I am looking for a similar form of validation (but without widening the type).