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.
This precisely is the minimum functionality I would like to see - we're not concerned about contextual typing, but working around either failed type inference or overload selection. And the easiest way to do this is to have a safe "upcast" that's checked to not also downcast.
On Wed, Aug 22, 2018 at 22:51 Magnus Hiie [email protected] wrote:
Which causes expr to be contextually typed by T, but the type of the entire expression is still expr's inferred type rather than T. @RyanCavanaugh https://github.com/RyanCavanaugh while I can see how this operator could be useful in some scenarios, your proposed operator is different from what I originally proposed. My proposed operator's type would be T, not typeof expr, and is useful for guiding bottom-up type inference and hiding too specific types, whereas the operator you described is mostly a documentation/debugging tool as it doesn't have any effect to the surrounding code.
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/7481#issuecomment-415299196, or mute the thread https://github.com/notifications/unsubscribe-auth/AERrBC_ro8xw4w-ZSGwTZsNBA0s-0CKYks5uTkKOgaJpZM4HurCq .
I also see a difference in what you propose @RyanCavanaugh. In its simplest form, what I believe is desired from this proposal is that (in my example) the abstract method push of the firebase handle gets the type assurance similar to the push of the typed array.

Ideally an is keyword, as was already suggested, is what seems to be the best fit. be would be also fine.
getFirebaseRef().push({} is MyItem)
getFirebaseRef().push({} be MyItem)
In this example, it is like using a type guard
const incompleteTasks = (tasks: Task[]) => tasks.filter(task => !(getWork(task.currentAssignment) is Todo).isComplete);
const incompleteTasks = (tasks: Task[]) => tasks.filter(task => !(getWork(task.currentAssignment) be Todo).isComplete);
// verbose, but eventually does the same thing
function isTodo(task: Todo | SomethingElse): task is Todo {
return (<Todo>task).isComplete !== undefined;
}
const incompleteTasks = (tasks: Task[]) => tasks.filter(task => {
const work = getWork(task.currentAssignment)
if (isTodo(work)) {
return !work.isComplete
} else {
throw new Error('Wrong Type!')
// actually we want a compile error, not runtime
}
});
@RyanCavanaugh I'm also wondering why you want expr SOMETHING T to be of expr inferred type instead of just T.
This still will be hugely useful feature, used quite often in many scenarios. But I don't see scenarios when I don't want the type to be T.
Like in here:

I want this type to be SomeInterface not { a: string; b: string: c: string; } because when I see this name in editor hints and error message I know what it is immedietely.
As for SOMETHING. I don't know. I kinda like is proposed earlier. Whatever you'll choose will be fine for me, just don't make it too long, because it will be used often 😜.
Or I'm missing the purpose of this proposal completely? Your proposal mean that expr SOMETHING T will throw compiler error is all cases when var t : T = expr throws also? right?
Scenarios where the expression type is more valuable -
// Today
const a: Partial<Point> = { x: 10 };
// Error, 'x' might be undefined
console.log(a.x.toFixed());
// OK, really shouldn't be
console.log(a.y!.toFixed());
// Desired
const a = { x: 10 } SOMETHING Partial<Point>;
// OK
console.log(a.x.toFixed());
// Error
console.log(a.y!.toFixed());
// Another example (Desired only):
type Neat = { [key: string]: boolean };
declare function fn(x: { m: boolean }): void;
const x = {
m: true
} SOMETHING Neat;
// Today: Should be OK, isn't
fn(x);
// Today: Should be error, isn't
console.log(x.z);
@mpawelski I think you're off-course here; your example involves a downcast (which is what everyone agrees needs to not be possible) and the display of the type there doesn't depend on any assertions
yep, I meant that as in downcast I want new operator to be of type T, maybe I didn't made it clear enough.
Anyway, your examples totally convinced me why it shouldn't. thanks!
@RyanCavanaugh What I would like is basically syntax for this:
function is<T>(value: T): T { return value }
// Syntax for this:
is<Foo>(value) // upcast to `Foo`
Technically, this is a checked upcast, whereas as is an unchecked one (it can cast down as well as up). But this above is the semantics of any operator I'd prefer.
Just thought I'd clarify what I'm looking for.
Edit: I meant to include an apology for crossing up wires here - I've been busy at a conference and just typed that on the fly. This comment is much more precisely what I want.
The fact that you can write upcast<T>(x: T): T yourself but can't write check<T>(x extends T): typeof x (??) is another reason we want any hypothetical new operator to return the expression type rather than the check type.
Yes, something like this: https://github.com/Microsoft/TypeScript/issues/27127
We punted a bunch of syntax ideas around but hated all of them.
Well, I don't know what kind of keyword team hated so I risk that I'll propose another one you'll hate 😨
I propose it to be assertis. I like it because it is short and has 'assert' inside and it's basically a compile-time assertion. It can only result in compile error, if there's no error then the result is the same as if we didn't use this language feature.
Some ramblings:
Possible names for SOMETHING: mustbe, satisfies, obeys.
Other idea: To avoid extending the expression syntax, put the static assertion on type annotations, rather than in expressions:
type HasM = { m: boolean };
type Neat = { [key: string]: boolean };
declare function fn(x: { m: boolean }): void;
const x: HasM mustbe Neat = {
m: true
}; // x is type HasM
In the case we want inference, maybe omit or use *?
const x: * mustbe Neat = {
m: true
};
// or
const x: mustbe Neat = {
m: true
}; // x is type HasM
Then possibly allow chaining:
const x: HasM mustbe Neat, { x: true }, object = {
m: true
}; // x is type HasM
Flow uses simply : for a very similar feature they call casting for some bizarre reason. They require a wrapping () to avoid ambiguity, which I think is fine in this context, since you aren't going to want to double contextually type unless you're doing something real weird like type testing.
Another precedent is Haskell, which uses :: for the same thing.
I would love this implemented to use with string literals, since this is valid but obviously wrong:
const x = { type: 'notanitem' as 'item', value: "example" }
If I have to write the string twice, at least the compiler should hint when I mess up.
// I vote for 'is'
const x = { type: 'item' is 'item', value: "example" }
// or flow style
const x = { type: ('item' : 'item'), value: "example" }
@fqborges what you are describing in the first part of your post is also called "sidecasting" and was marked as "working as intended" in #16995. However, I've written a lint rule to detect this so you don't mess up: https://github.com/fimbullinter/wotan/blob/master/packages/mimir/docs/no-invalid-assertion.md
SOMETHING:
mustbe,
shouldbe,
satisfies, satisfying
obeys.
matches,
is, be,
compares
assertis
complements,
parallels,
achieves ,
realizes,
fulfils,
withtype
There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton
I like satisfies or withtype.
TypeHintExpression ::
Expression withtype Type
Expression satisfying Type
is is my pref and it has a nice corollary with as
I wanted to set aside the syntax conversation for a moment and collect some "real-world" use cases for where this operator would be useful.
e.g.
declare function paint(color: Color): void;
export type Color = { r: number, g: number, b: number };
// All of these should be Colors, but I only use some of them here.
// Other modules are allowed to use any of these properties.
// I have no way to find the typo here:
export const Palette = {
white: { r: 255, g: 255, b: 255},
black: { r: 0, g: 0, d: 0},
blue: { r: 0, g: 0, b: 255 },
} /* ??op?? Record<string, Color> */;
// ^^^ would cause the error to be identified
paint(Palette.white);
paint(Palette.blue);
// Correctly errors, but wouldn't if Palette were Record<string, Color>
paint(Palette.blur);
Heres a hacky way of doing it (error messages are poor).
export type Color = { r: number, g: number, b: number };
const check = <U>(x: U) => <T extends U extends T ? unknown : [U, 'not assignable to', T]>(): U => x;
export const Palette = check({
white: { r: 255, g: 255, b: 255},
black: { r: 0, g: 0, d: 0},
blue: { r: 0, g: 0, b: 255 },
})<Record<string, Color>>();
I wanted to set aside the syntax conversation for a moment and collect some "real-world" use cases for where this operator would be useful.
My main use case that appears a lot is in my example above (https://github.com/microsoft/TypeScript/issues/7481#issuecomment-438709565).
const x = { type: 'item', value: "example" }; // 'item' as 'item' literal not string
What I noticed is that in the latest versions of TypeScript most of the time when I just use the above it infers the literal type.
The second use case is just hint the type on the middle of an object, without being obliged to declare the the object as a whole. Example:
const myConfig = {
name: 'foobar',
uri: 'foo://bar',
// ...
// imagine a lot of props with distinct shapes here
// ...
palette: {
white: { r: 255, g: 255, b: 255},
black: { r: 0, g: 0, d: 0},
blue: { r: 0, g: 0, b: 255 },
} as Record<string, Color>
}