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.
I recently posted another use case to StackOverflow. I'm generating an API from a structure and need the structure to have a certain conformation while still preserving its unique type.
All I'd like is a declarative shorthand for the following function:
function assertTemplate<T extends Template>(template: T) {
return template;
}
Maybe something like:
const api: ConformsTo<Template> = {
// ...
};
Which would be equivalent to:
const api = assertTemplate({
// ...
});
Most of the time I tend to do something like this:
export const STRING_CONVERT = {
num: (num: number) => num.toString(),
bool: (bool: boolean) => (bool ? "yes" : "no"),
};
// Check that STRING_CONVERT only includes functions that return strings.
STRING_CONVERT as Record<string, (v: unknown) => string>;
I know this leaves a random STRING_CONVERT; in the code but tree shaking cleans it up (maybe?). Flow has assertion syntax (using :) that does get removed from output so I started doing something similar when I switched to TS.
But I agree the following with implements is much cleaner (and a great suggestion!):
export const STRING_CONVERT = {
a: (num: number) => num.toString(),
b: (bool: boolean) => (bool ? "yes" : "no"),
} implements Record<string, (v: unknown) => string>;
@dhoulb Your example highlights why as and its downcasting behaviour is bad at doing assertions like that
export const STRING_CONVERT = {
// woops, the actual return type here is 0 | string
num: (num: number) => num && num.toString(),
};
// Passes type check without errors :(
STRING_CONVERT as Record<string, (v: unknown) => string>;
whereas
const _check: Record<string, (v: unknown) => string> = STRING_CONVERT;
would give you an error as expected.
I recently posted another use case to StackOverflow. I'm generating an API from a structure and need the structure to have a certain conformation while still preserving its unique type.
All I'd like is a declarative shorthand for the following function:
function assertTemplate<T extends Template>(template: T) { return template; }Maybe something like:
const api: ConformsTo<Template> = { // ... };Which would be equivalent to:
const api = assertTemplate({ // ... });
I usually have a use case very similar to @jtlapp, but I think it's specially relevant when there are generics in between.
Simplified example, I have an interface with a generic:
interface ColumnDefinition<M, T> {
id: string,
selector: (model: M) => T,
renderer: (value: T) => JSX.Element
}
If I want to instantiate a variable with this type, I have to put the generics in:
const labelColumn: ColumnDefinition<Todo, string> = {
id: 'label'
selector: todo => todo.label,
renderer: label => ...
}
and I can't avoid it directly. If I put in any for the generics (or default them), then renderer will have "label" as any too. I usually have the same identity function that does the inference for me:
function colDef<M, T>(columnDefinition: ColumnDefinition<M, T>) {
return columnDefinition
}
const labelColumn = colDef({
id: 'label'
selector: (todo: Todo) => todo.label,
renderer: label => ... // T inferred nicely as string
})
I have a situation for which I haven't found a workaround. I want each element of an array to conform to the same abstract structure without requiring all the elements to be of the same type. I can't use classes because I'm dictating that all object members have a certain structure, regardless of their names.
It seems that the ConformsTo<T> proposal would address this:
function processRecords(records: ConformsTo<RecordStructure>[]) {
...
}
The problem is that each element of the array can have a different set of properties.
UPDATE. Here's a workaround, but I think it's too awkward to use in a utility API:
type CheckedApi = { [key: string]: (...args: any[]) => Promise<any> };
function checkApi<T extends ServerApi<T>>(api: T) {
return api as CheckedApi;
}
class Api1 {
async func1() {}
}
class Api2 {
async func2() {}
}
function exposeApis(_apis: CheckedApi[]) {}
const api1 = new Api1();
const api2 = new Api2();
exposeApis([checkApi(api1), checkApi(api2)]);
I think #33480 (a proposal for referencing the inferred type on the LHS) could also address many of the use cases here
I would like to point out yet another workaround, It works in current TypeScript v4.5.2.
type Same<P,T> = P extends T? (T extends P? 1: 0): 0
const verifySame = <P> () => <T> (_: Same<P,T>, t:T): T => t
type Hello = {hello: string}
verifySame<Hello>()(1, {hello: "world"})
verifySame<Hello>()(0, {hello: "world", since : 2020})
//this will not compile:
//Argument of type '1' is not assignable to parameter of type '0'.ts(2345)
//verifySame<Hello>()(1, {hello: "world", since : 2020})
verifySame has a higher rank type but appears to be supported by TS.
verifySame should provide type safety preventing subtyping.
To clarify my comment, the rank-2 is convenient in some case but often not needed. Cleaning up my above example (replacing literal numbers with literal booleans) here is a safe invariant version of the array push:
//Cleaner version of the above 'Some' uses literal booleans
type Same<P,T> = P extends T? (T extends P? true: false): false
//Note to get safety I end up with casting, this is quick and dirty but still ...
const safePush = <P, T> (_: Same<P,T>, ps: P[], t: T): number => ps.push(t as any)
const intlist: number[] = [1,2,3]
const list: unknown[] = intlist //exploits array covariance
list.push("not a number") //TS push adds 'string' to 'intlist'
safePush(true, intlist, 1) //this is safe
//safePush(true, list, 1) //this is risky and will not compile
//safePush(true, list, "not a number") //this is risky (here wrong) and will not compile
This does not use rank-2 tricks. It shows how such work-around could be used in APIs.
I have some open questions based on playing with the PR and would like to hear people's thoughts
/* ~~ Example 1 ~~ */
const x = [1, 2] satisfies [number, number];
// What is the type of 'x' ?
// Argument for [number, number]:
// If [1, 2] isn't a [number, number], then the 'satisfies' should have been rejected, but it wasn't
// Argument for number[]:
// This operator is not supposed to change the type of the expression (except to remove implicit anys)
/* ~~ Example 2 ~~ */
type Disposable = {
dispose(): void;
beforeDispose?(): void;
};
const s = {
init() {
// Allocate
},
dispose() {
// Cleanup
}
} satisfies Disposable;
// Is 'init' an excess property here?
// Argument for:
// If instead of 'init' we had written 'beforDispose' [sic],
// failing to flag that as an error is a clear deficit
// Argument against:
// This code sure looks fine. You could have written
// } satisfies Disposable & Record<string, unknown>
// instead if you were OK with excess properties
/* ~~ Example 3 ~~ */
let y = 3 satisfies 3;
let z: 3 = y;
// Is this a correct error?
// Argument for: This operator is not supposed to change the types. You could have written 'as const' or 'as 3' instead.
// Argument against: I literally just checked that this is 3!
My understanding was that the purpose of satisfies was not just to check for assignability, but also to trigger contextual typing, so I don’t find the fact that it changes the inferred type from array to tuple surprising. It’s quite useful that way, as it can do what would have required a constrained identity function without it.
I would find the operator much less useful if it only filled in implicit anys. One of the use cases that immediately came to mind when I found out about this change was this:
const foo = null satisfies string | null;
// instead of:
// const foo: string | null = null as string | null
…which wouldn’t work if satisfies couldn’t change the inferred type.
Relatedly, I would also intuitively expect cat satisfies Animal to be an upcast.
const foo = null satisfies string | null;
Based on prior discussion, I don't think we want foo to be string | null here. The reason is that, using the example from my prior comment, you want to be able to call s.init() -- this implies we should use the expression type, not the asserted type.
I was assuming that init in that example was going to be treated as an excess property, consistent with satisfies being a contextual-typing hint.
I guess I find any solution where satisfies can’t change the type of an expression to be potentially confusing, since the type of an expression is usually affected by contextual typing anyway. It just seems natural that “the contextual typing operator” should be able to change the type of an expression. It’s more mental overhead if I have to remember that satisfies contextually types an expression, but doesn’t affect its type like other cases of contextual typing do. TypeScript IMO has way too many of these special cases already.
I'm here hoping for a conforms-to assertion for ensuring that multiple different types conform to the same type and still remain their respective different types after the assertion. Changing the type completely undermines my scenarios, described above here and here. Please let me know if I posted to the wrong issue, as type-preservation is fundamental to what I need to accomplish.
// What is the type of 'x' ?
If the type of x is not affected by satisfies and [1, 2] satisfies [number, number] becomes number[] again, then I guess you loose the ability to use this feature to annotate individual properties of objects? Expression level type annotations could be very handy to avoid boilerplate when you have lots of properties on an object and would rather not repeat them in the type definition and its implementation. I.e. I'd like the following to error, as it currently does in the playground
function createThing(str: string) {
return {
foo: [str] satisfies [string],
}
}
createThing('foo').foo[1].toUpperCase()
// ^ Should not be allowed to access index 1 of [string]
// Is 'init' an excess property here?
Yes please. Guarding against excess properties (which are often typos, leftovers from old APIs or other mistakes) is a common need and being able to do it inside arbitrary expressions would be very handy.
Basically I was hoping just expression-level : , which I use quite often in Flow.
I guess this directly conflicts with @jtlapp 's use cases though.
// Is this a correct error?
Seems weird to me.
Why x = [1, 2] satisfies [number, number] is [number, number] but 3 satisfies 3 is not 3? :thinking:
I hope that's what this feature means - but a good scenario is combining as const with type annotation. Currently there is no way to say const a = {a: 2} as const satisfies Record<string, number> which in this case will make sure the object follows the record structure but at the end the type will be the actual const asserted type.
@jtlapp If I understand your use-case correctly, you can already do something like
type ApiTemplate = {
[funcName: string]: {
call: (data: any) => void;
handler: (data: any) => void;
}
};
const apiConfig1 = {
func1: {
call: (count: number) => console.log("count", count),
handler: (data: any) => console.log(data),
},
func2: {
call: (name: string) => console.log(name),
handler: (data: any) => console.log("string", data),
},
}
// Currently working way to do type validation without any runtime impact
const _typecheck: ApiTemplate = null! as typeof apiConfig1
// TS can still autocomplete properties func1 and func2 here,
// and errors for missing "func". apiConfig1 is not merely "ApiTemplate".
apiConfig1.func
The unfortunate thing about that approach is that it involves using an extra unused variable, which tends to make linters mad. satisfies would fix this, as you could instead do
// Assert that apiConfig1 is a valid ApiTemplate
null! as typeof apiConfig1 satisfies ApiTemplate
Thank you, @noppa. I actually do have my code working, but it's missing an important piece, which it seems that I didn't overtly say in my use cases above:
I want VSCode highlighting the errors in the user's custom ApiTemplate definition, rather than at a later point in the code where the user passes that custom definition to some function.
The goal is to facilitate correct API development at the point where the API code is written.
I'm close to sharing my project to provide better clarity on the problem I'd like to solve. I just need to document it. I've found the Electron IPC mechanism so-many-ways error prone, and I've developed a way to create IPCs merely by creating classes of asynchronous methods, registering these classes on one end, and binding to them on the other. The entire objective is to make life as easy and bug-free as possible for the developer. I'm actually pretty amazed that I was able to do it. The only thing lacking at this point is having VSCode indicate API signature errors in the API code itself. I used to think the TypeScript type system was excessively complicated, but now I'm addicted to its power.
The only way satisfies is useful to me is if it does provide additional context to the inferred type.
Use case: providing more accurate types for object literal properties. This is particularly useful in something like Vue Options API where everything is declared in an object literal.
@RyanCavanaugh I took a look at your questions above, and these are my thoughts:
Example 1
const x = [1, 2] satisfies [number, number]; // What is the type of 'x' ? // Argument for [number, number]: // If [1, 2] isn't a [number, number], then the 'satisfies' should have been rejected, but it wasn't // Argument for number[]: // This operator is not supposed to change the type of the expression (except to remove implicit anys)
In this case, I'd expect the type of x to be [number, number], for two reasons:
- The type of the expression
[1, 2]isnumber[], but since[1, 2]is assignable to type[number, number], and since[number, number]is more specific thannumber[], I expect the type of the overall expression to be[number, number] - My mental model of the
satisfiesoperator is essentially "assume at least this shape if (and only if) it's safe to do so", rather than "verify that it would be possible to assume this shape"
Example 2
type Disposable = { dispose(): void; beforeDispose?(): void; }; const s = { init() { // Allocate }, dispose() { // Cleanup } } satisfies Disposable; // Is 'init' an excess property here? // Argument for: // If instead of 'init' we had written 'beforDispose' [sic], // failing to flag that as an error is a clear deficit // Argument against: // This code sure looks fine. You could have written // } satisfies Disposable & Record<string, unknown> // instead if you were OK with excess properties
This is a tricky one.
At first I was going to make the argument that this case should raise an excess property error specifically because this code does:
const s: Disposable = {
init() { ... },
dispose() { ... }
};
However, I realised that such behaviour would contradict my mental model of the operator.
I mentioned above that my mental model of satisfies was essentially "assume at least this shape if (and only if) it's safe to do so". That "at least" bit is important, because it means that if the LHS is of a more specific type than the RHS (while still being assignable to the RHS), then I expect the overall type of the satisfies expression to be that of the LHS, not the RHS.
For example:
const value1 = (3 as const) satisfies number; // `value1` should be of type `3`
const value2 = ([1, 2, 3] as [1, 2, 3]) satisfies number[]; // `value2` should be of type `[1, 2, 3]`
So, revisiting the example from the question with this in mind:
type Disposable = {
dispose(): void;
beforeDispose?(): void;
};
const s = {
init() { ... },
dispose() { ... }
} satisfies Disposable;
I would expect the type of s to be
{
init(): void;
dispose(): void;
}
and because the type of s is not specifically Disposable, I would not expect to see an excess property error.
Example 3
let y = 3 satisfies 3; let z: 3 = y; // Is this a correct error? // Argument for: This operator is not supposed to change the types. You could have written 'as const' or 'as 3' instead. // Argument against: I literally just checked that this is 3!
I feel like this should not be an error.
My interpretation of this code is basically the same as the first example. The type of the expression 3 is number, but since 3 is assignable to type 3, and since 3 is more specific than number, I expect the type of the overall expression to be 3. As a result, I expect y to be of type 3, and thus its assignment to z to succeed.
I hope that helps! 🙂
Also, please let me know if my mental model of satisfies is incorrect in any way, as if it is, most of what I've said here will probably be invalid! 😁