UPDATE FOR TS4.9+
Exciting news for TypeScript 4.9 and beyond—introducing the new `satisfies` operator. This operator allows you to contextually check a value against a type without actually assigning it that type, eliminating the need for a helper function. Here's how it works:
const x = {
a: 1,
b: 'test'
} satisfies ObjType // no problem here
type XType = typeof x;
/* type XType = {
a: number;
b: string;
} */
const oops = 123 satisfies ObjType; // error!
Check out this Playground link for code
PREVIOUS ANSWER FOR TS4.8-
To deal with TypeScript versions prior to 4.9, you can utilize a workaround by creating a generic helper function as shown below:
const asObjType = <T extends ObjType>(t: T) => t;
The `asObjType` function returns its input `t` without altering the type `T`, which is constrained to `ObjType`. Instead of explicitly annotating `x` as `ObjType`, you assign the output of `asObjType` to it. Let's see this in practice:
const x = asObjType({
a: 1,
b: 'test'
});
type XType = typeof x;
/* type XType = {
a: number;
b: string;
} */
Everything seems to be working smoothly. Additionally, the function blocks non-`ObjType` values from passing through:
const oops = asObjType(123); // error!
// ------------------> ~~~
// Argument of type 'number' is not assignable to parameter of type 'ObjType'
All good on that front.
Explore the code further on the Playground