Operator to ensure an expression is contextually typed by, and satisfies, some type
Sometimes it's necessary (e.g. for guiding type inference, for ensuring sub-expression conforms to an interface, or for clarity) to change the static type of an expression. Currently TypeScript has the as (aka <>) operator for that, but it's dangerous, as it also allows down-casting. It would be nice if there was another operator for implicit conversions only (type compatibility). I think this operator should be recommended in most cases instead of as.
This operator can be implemented as a generic function, but as it shouldn't have any run-time effect, it would be better if it was incorporated into the language.
function asType<T>(value: T) {
return value;
};
EDIT: Due to parameter bivariance, this function is not equivalent to the proposed operator, because asType allows downcasts too.
Also, please let me know if my mental model of satisfies is incorrect in any way
Right now there are no wrong answers -- the point of the exercise to determine what the "right" mental model of this operator should be!
I would expect something to exactly like inference for generic constrained arguments, if that helps. If there's an obviously wrong behavior for one then it's probably also wrong for the other.
@simonbuchan I agree. I guess that you could model the spec to this function:
export function satisfies<A>() {
return <T extends A>(x: T) => x;
}
If we then look @RyanCavanaugh examples, then it corresponds with @treybrisbane mental model:
/* ~~ Example 1 ~~ */
const x = satisfies<[number, number]>()([1, 2]);
// type is inferred as [number, number]
/* ~~ Example 2 ~~ */
type Disposable = {
dispose(): void;
beforeDispose?(): void;
};
const s = satisfies<Disposable>()({
init() {
// Allocate
},
dispose() {
// Cleanup
},
});
// Is 'init' an excess property here?
// No error here. And the type is inferred as: { init(): void, dispose(): void }
/* ~~ Example 3 ~~ */
let y = satisfies<3>()(3);
let z: 3 = y;
// There is no error, type of y is inferred as 3
Also the other examples:
const value1 = satisfies<number>()(3 as const); // `value1` is of type `3`
const value2 = satisfies<number[]>()([1, 2, 3] as [1, 2, 3]); // `value2` is of type `[1, 2, 3]`
// and another one
const value3 = satisfies<ReadonlyArray<number>>()([1, 2, 3] as const); // `value3` is of type `readonly [1, 2, 3]`
@kasperpeulen thanks for the code and examples! Glad to see it works out, I wasn't on a computer and couldn't figure out what the satisfies function would look like.
I'd like to interject a slight tangent (pessimistically, scope creep?) that I haven't seen pointed out yet, but I think would be a good use case for any keyword introduced for these static checks. Specifically, some generic constraints are impossible to express due to circular references, and unlike top-level variable/expression type constraints, there's no other place to even put a dead assignment to get the check.
This has come up for me a number of times as a framework author wanting to type my APIs as tightly as possible to prevent accidental misuse. Most recently, I was trying to write an "isEnum" type guard (see also #30611):
function isEnum<T extends Enum<T>>(enumContainer: T): (arg: unknown) => arg is T[keyof T] { ... }
type Enum<T, E = T[keyof T]> =
[E] extends [string] ? (string extends E ? never : unknown) :
[E] extends [number] ? (
true extends ({[key: number]: true} & {[P in E]: false})[number] ?
unknown : never) :
never;
Unfortunately, because of the [P in E] index required to work around #26362, TypeScript sees a circular reference and can't handle the T extends Enum<T>, but a human can look at this and see that this is not so much a type bound (that needs to be resolved in order to typecheck the body of the function), but rather a type constraint that only matters for checking callsites. This seems like an excellent use case for function isEnum<T satisfies Enum<T>> or function isEnum<T implements Enum<T>>, which would check the constraint for callers, but not have a problem with circularity.
The reason this is a good fit is that there's no other good place to do this check, due to how TypeScript does its type checking. In C++, you can write a static_assert in the body of the function, and since it re-typechecks each generic function with every new instantiation, it works. But TypeScript uses the template bounds to type check the function body once, and from then on callers are reduced to just checking the template bounds - so this allows more extensive verification that the types passed into the templates are actually reasonable.
FWIW, my current workaround is pretty ugly and doesn't work universally. It essentially boils down to
type NotAnEnum = {__expected_an_enum_type_but_got__: T};
type EnumGuard<T> = ... ? (arg: unknown) => arg is T[keyof T] : NotAnEnum<T>;
function isEnum<T>(enumContainer: T): EnumGuard<T> { ... }
This gets the job done, but as folks upthread have pointed out, it moves the error from the construction to the usage - because the isEnum function typechecks no matter what, it just returns an unusable value. This also relies on there being usable and unusable values: if the function returned void, for instance, this wouldn't work so well.
EDIT: added syntax highlighting
One other reason in favour of allowing satisfies to "assume at least this shape if (and only if) it's safe to do so".
When working with a lot of tuples, I often have the following problem:
declare function getTuple(): [number, number];
declare function calculate(tuple: [number, number]): number;
declare function memo<T>(factory: () => T): T;
function foo() {
const [a, b] = getTuple();
const tuple = memo(() => [b, a * 2]);
// TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number]'.
// Target requires 2 element(s) but source may have fewer.
return calculate(tuple);
}
I think most people would first as const, but that gives another problem:
function foo() {
const [a, b] = getTuple();
const tuple = memo(() => [b, a * 2] as const);
// TS2345: Argument of type 'readonly [number, number]' is not assignable to parameter of type '[number, number]'.
// The type 'readonly [number, number]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.
return calculate(tuple);
}
So now, what do you do? You have two options:
-
one is to change the parameter of
calculateto be areadonly [number, number], which is fine, but also feels a bit arbitrary if you are not using readonly types in the rest of the project, and sometimes it means that many functions need to be refactored to readonly. -
the other option is, to not use
as const, but useas [number, number]. This seems like a solid solution, but it is actually quite dangerous, because what if now a refactor made getTuple to returndeclare function getTuple(): [number, number | undefined];You may think that you could safely do this refactor in strict typescript, while my code stays sound, but no!
declare function getTuple(): [number, number | undefined];
declare function memo<T>(factory: () => T): T;
declare function calculate(tuple: [number, number]): number;
function foo() {
const [a, b] = getTuple();
// No error, but this code is not sounds anymore, silently converting number | undefined to a number
const tuple = memo(() => [b, a * 2] as [number, number]);
return calculate(tuple);
}
With satisfies, this could be done in a sound way:
declare function getTuple(): [number, number | undefined];
declare function memo<T>(factory: () => T): T;
declare function calculate(tuple: [number, number]): number;
function foo() {
const [a, b] = getTuple();
// This will not compile. The type need to be changed to [number | undefined, number] or the null value must be handled.
const tuple = memo(() => [b, a * 2] satisfies [number, number]);
return calculate(tuple);
}
Here's another use case to consider:
import type { RequestHandler } from 'express'
interface RouteHandlers {
login: RequestHandler
logout: RequestHandler
}
export const routeHandlers: RouteHandlers = {
login(req, res) {
...
},
logout(req, res, next) {
...
}
}
satisfies would certainly make this more DRY:
export const routeHandlers = {
login: ((req, res) => satisfies<RequestHandler>({
...
})),
logout: ((req, res) => satisfies<RequestHandler>({
...
})),
}
...although in this case I can envision some syntax that would be even more concise, given that every value in the object should be a function of type RequestHandler. Obviously there are more important things than just being concise, just wanted to share the use case.
To summarise what I recorded in the other issue (before I was helpfully referred to this feature discussion) and responding to @RyanCavanaugh ....
What is the type of 'x'
What I expected from a like operator - it would do nothing at all to the types of any existing language construction, but it WOULD raise compiler errors if the item cannot be known to satisfy the definition.
So for cases where the type IS satisfied it's a passthrough, and nobody has to reason about it at all, while if it ISN'T satisfied, then it would raise errors just like an assignment to a type (including excess property checks for literals) giving local and immediate feedback that it wasn't like the type you asked.
I'd like to pick up the conversation at #47920 to get a clean comment slate. There's a large write-up there.
I would suggest something simple like
Case 1 ("strict cast"):
{prop: 123} as! MyInterface // fails on missing properties or properties not satisfying MyInterface
Case 2 ("safe cast")
{prop: 123} as? MyInterface // returns null if cast not successful
Case 3 ("unsafe cast")
{prop: 123} as MyInterface // just labels the object as the specified interface (currently the only possibility)