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.
Can you post a few examples of how you'd like this to work so we can understand the use cases?
One example very close to the real-world need (I'm trying to get react and react-redux typings to correctly represent the required/provided Props):
import { Component } from "react";
import { connect } from "react-redux";
// the proposed operator, implemented as a generic function
function asType<T>(value: T) {
return value;
};
// in real life, imported from another (actions) module
function selectSomething(id: string): Promise<void> {
// ...
return null;
}
interface MyComponentActions {
selectSomething(id: string): void;
}
class MyComponent extends Component<MyComponentActions, void> {
render() {
return null;
}
}
// I've changed the connect() typing from DefinitelyTyped to the following:
// export function connect<P, A>(mapStateToProps?: MapStateToProps,
// mapDispatchToProps?: MapDispatchToPropsFunction|A,
// mergeProps?: MergeProps,
// options?: Options): ComponentConstructDecorator<P & A>;
// fails with "Argument of type 'typeof MyComponent' not assignable" because of
// void/Promise<void> mismatch - type inference needs help to upcast the expression
// to the right interface so it matches MyComponent
export const ConnectedPlain = connect(undefined, {
selectSomething,
})(MyComponent);
// erronously accepted, the intention was to provide all required actions
export const ConnectedAs = connect(undefined, {
} as MyComponentActions)(MyComponent);
// verbose, namespace pollution
const actions: MyComponentActions = {
selectSomething,
};
export const ConnectedVariable = connect(undefined, actions)(MyComponent);
// using asType<T>(), a bit verbose, runtime overhead, but otherwise correctly verifies the
// expression is compatible with the type
export const ConnectedAsType = connect(undefined, asType<MyComponentActions>({
selectSomething,
}))(MyComponent);
// using the proposed operator, equivalent to asType, does not compile yet
export const ConnectedOperator = connect(undefined, {
selectSomething,
} is MyComponentActions)(MyComponent);
I've called the proposed operator in the last snippet is.
The other kind of scenario is complex expressions where it's not immediately obvious what the type of the expression is and helps the reader understand the code, and the writer to get better error messages by validating the subexpression types individually. This is especially useful in cases of functional arrow function expressions.
A somewhat contrived example (using the tentative is operator again), where it's not immediately obvious what the result of getWork is, especially when it's a generic function where the result type depends on the argument type:
const incompleteTasks = (tasks: Task[]) => tasks.filter(task => !(getWork(task.currentAssignment) is Todo).isComplete);
I ran into something similar when I was patching up code in DefinitelyTyped - to get around checking for excess object literal assignment, you have to assert its type, but that can be a little extreme in some circumstances, and hides potential issues you might run into during a refactoring.
There are also scenarios where I want to "bless" an expression with a contextual type, but I don't want a full blown type assertion for the reasons listed above. For instance, if a library defines a type alias for its callback type, I want to contextually type my callback, but I _don't_ want to use a type assertion.
In other words, a type assertion is for saying "I know what I'm going to do, leave me a alone." This is more for "I'm pretty sure this should be okay, but please back me up on this TypeScript".
Sounds a lot like #2876?
If I understand #2876 correctly, it's still a downcast (i.e. bypassing type safety). What I was proposing here is an upcast (i.e. guaranteed to succeed at runtime or results in compile time error). Also, while <?> seems a bit like magic, the is operator is as straightforward as assigning to a variable with a defined type or passing an argument to a function with a parameter that has a defined type.
I think the best example of this operator exists in the Coq language:
Definition id {T} (x: T) := x.
Definition id_nat x := id (x : nat).
Check id_nat.
id_nat
: nat -> nat
Here, the expression x : nat is a type cast, where Coq's type cast is not dynamic but static (and mostly used in generic scenarios, like the ones I mentioned above) - here it means id_nat's argument type is restricted to be a nat.
Another case for this is when returning an object literal from a function that has a type union for it's return type such as Promise.then.
interface FeatureCollection {
type: 'FeatureCollection'
features: any[];
}
fetch(data)
.then(response => response.json())
.then(results => ({ type: 'FeatureCollection', features: results }));
This gets quite tricky for intellisense in VS because the return type from then is PromiseLike<T> | T. Casting allows intellisense to work, but as mentioned it can hide errors due to missing members.
Also the error messages when the return value is invalid are quite obtuse because they refer to the union type. Knowing the intended type would allow the compiler to produce a more specific error.
@chilversc I'm not sure how an upcast can help with your example. Could you show how it would be used, using the above asType
Odd, I thought I had a case where an assignment such as let x: Foo = {...}; would show a compile error while a cast such as let x = <Foo> {...}; would not.
The cast was required to get the object literal to behave correctly as in this case:
interface Foo {
type: 'Foo',
id: number;
}
let foo: Foo = { type: 'Foo', id: 5 };
let ids = [1, 2, 3];
//Error TS2322 Type '{ type: string; id: number; }[]' is not assignable to type 'Foo[]'.
//Type '{ type: string; id: number; }' is not assignable to type 'Foo'.
//Types of property 'type' are incompatible.
//Type 'string' is not assignable to type '"Foo"'.
let foosWithError: Foo[] = ids.map(id => ({ type: 'Foo', id: id }));
let foosNoErrorCast: Foo[] = ids.map(id => ({ type: 'Foo', id: id } as Foo));
let foosNoErrorAssignment: Foo[] = ids.map(id => {
let f: Foo = {type: 'Foo', id: id};
return f;
});
Could we just use is the same way as as ?
interface A {
a: string
}
let b = {a: 'test'} as A // type: A, OK
let c = {a: 'test', b:'test'} as A // type: A, OK
let d = {a: 'test'} is A // type: A, OK
let e = {a: 'test', b:'test'} is A // error, b does not exist in A
@wallverb that is really clever and really intuitive. Interestingly, it also provides a manifest way of describing the difference between the assignability between fresh object literals target typed by an argument vs existing objects that conform to the type of that argument.
I like this idea of effectively a static type assertion.
@normalser your example about let e = {a: 'test', b:'test'} is A is to me still an up-cast and should succeed as proposed by this issue. I think your expectation is more towards #12936. Although if A is an exact type (as proposed in #12936), the is operator would error as well.
Also linking #13788 about the current behavior of the type assertion operator as being both upcast and downcast.
I'm new to TypeScript but have already had a need for something like this. I've been Googling for a while now and looked in the TypeScript docs and can't find what I need. I'm really surprised since I assume this capability MUST exist. I think I ran into the problem trying to use Redux and wanted to ensure that I was passing a specific type of object to the connect function. Once I specify the type hint - "this is supposed to be a X" - I'd like the editor to do intellisense and show me what properties need to be filled in, so maybe the type name needs to come first like a safe cast expression.
function doSomething(obj: any) { }
interface IPoint {
x: number;
y: number;
}
// This does what I expect. I'm making sure to pass a correct IPoint
// to the function.
let point: IPoint = { x: 1, y: 2 };
doSomething(point);
// But is there a more concise way to do the above, without introducing a
// temporary variable? Both of these compile but it isn't safe since my IPoint
// is missing the y parameter.
doSomething(<IPoint>{ x: 1 });
doSomething({ x: 1 } as IPoint);
// How about this type of syntax?
doSomething(<IPoint!>{ x: 1 });
doSomething(<Exact<IPoint>>{ x: 1 });
doSomething((IPoint = { x: 1 }));
doSomething({ x: 1 } as IPoint!); // for JSX
doSomething({ x: 1 } is IPoint);
doSomething({ x: 1 } implements IPoint);
@DanielRosenwasser I feel like there must be some way at this point to use mapped types or something to write something that breaks the comparability relationship in a way that it only allows subtypes through?
Actually this would work for me. I just need to create a custom function that I use wherever I need an exact type. Seems kind of obvious in retrospect. I'm still surprised this kind of thing isn't built-in.
function exact<T>(item:T): T {
return item;
}
doSomething(exact<IPoint>({x:1, y:2}));
I am also looking for a way to specify the type of an inline object I am working with, so that when I ctrl+space I get hints and warnings.

By using as I get hints, but it is dangerous as I get no warnings for missing or unknown keys.
There already are type guards that use the parameterName is Type
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
It would be nice to also have this:
getFirebaseRef().push({} is MyItem)
-> now I would get hints for object properties -> now I would get errors for missing and unknown properties

Does this belong to this issue? (Allow a way to point the type checker to strictly infer strings and numbers as constants)
Update from suggestion review - there are a bunch of scenarios where we want a syntax that looks something like
expr SOMETHING T
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. An error occurs if expr is not assignable to T (assignability in the other direction is not sufficient).
The problem is what SOMETHING is. We punted a bunch of syntax ideas around but hated all of them. extends sounds too much like it does a runtime thing; typeof is taken; really all new expression syntax is super suspect, etc.. So we're basically blocked on finding some palatable syntactic space for this. Open to ideas but we're not super hopeful yet.
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 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.