Currently, there isn't a type operator in TypeScript 4.4 that checks if a value is assignable to a specific type without widening it to that type. An open feature request for such an operator exists at microsoft/TypeScript#7481. If you wish to support this request, consider adding your input on the GitHub issue.
Unfortunately, there are only workarounds available at the moment.
This answer will briefly explore some of these workarounds, which you may find academically interesting or useful for future reference.
One workaround involves using a helper function as seen in your question. While it incurs minimal runtime impact, it provides a viable approach to handle the situation.
If avoiding any runtime impact is crucial, you can create type functions within the type system to achieve similar outcomes:
const abc = {
a: "a",
b: "b",
c: "c"
};
type ABC = typeof abc;
type Extends<T extends U, U> = void;
type TestABC = Extends<ABC, Record<string, string>>; // valid
The Extends<T, U>
type function does not produce a meaningful result but triggers a compiler warning if T
does not extend U
.
// Example triggering a compilation error
const abc = {
a: "a",
b: 123,
c: "c"
};
type ABC = typeof abc;
type Extends<T extends U, U> = void;
type TestABC = Extends<ABC, Record<string, string>>; // results in error
All additional information is stripped during runtime execution.
Another workaround involves disregarding constraints completely and expecting external factors to flag potential issues. For instance, by defining:
const abc = {
a: "a",
b: "b",
c: "c"
};
and relying on subsequent code segments to signal any mismatches:
declare function doSomethingLater(x: Record<string, string>): void;
doSomethingLater(abc); // validates assignment
doSomethingLater(abc); // errors out with mismatch details
If no part of the code base raises concerns regarding the compatibility of abc
, reconsider the necessity of enforcing such constraints. However, if issues persist, revert to previously mentioned workarounds.
Link to TypeScript Playground Code