TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Operator to ensure an expression is contextually typed by, and satisfies, some type

Open magnushiie opened this issue 10 years ago • 90 comments

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.

magnushiie avatar Mar 11 '16 13:03 magnushiie

Is a prefix operator an option? This would allow for intellisense to provide completions and avoid typos as you go.

matt-tingen avatar Aug 08 '19 15:08 matt-tingen

Is a prefix operator an option? This would allow for intellisense to provide completions and avoid typos as you go.

We're a bit torn on this one. You're correct that putting the type before the expression is much better for completions, but at the same time we've been pushing people toward e as T for a while and it seems like a natural fit to have any new operation be of the same form. But if someone finds a really good prefix syntax, that would be a big win.

RyanCavanaugh avatar Aug 08 '19 16:08 RyanCavanaugh

Is the construction bellow possible without conflicting with current usings of <>?

const myConfig = {
  name: 'foobar',
  uri: 'foo://bar',

  <Record<string, Color>>palette: {
    white: { r: 255, g: 255, b: 255},
    black: { r: 0, g: 0, d: 0},
    blue: { r: 0, g: 0, b: 255 },
  }
}

Edited!

fqborges avatar Aug 08 '19 17:08 fqborges

Could you elaborate on the rationale for discouraging <T>e?

If the primary concern is with the parsing look-ahead when used with JSX, perhaps something like <:T>e could be used to keep the look-ahead at a constant 1 character peek. That notation is reminiscent of type annotations so it feels a bit more TypeScript-y to me.

matt-tingen avatar Aug 08 '19 17:08 matt-tingen

@matt-tingen If you are asking me, I am not against it. I just wrote faster than my head could elaborate my question/suggestion. 😅

fqborges avatar Aug 08 '19 17:08 fqborges

@fqborges I was meaning to ask @RyanCavanaugh. I feel like I remember seeing somewhere that the look-ahead added some complexity, but I wasn't sure if that was the main reason for encouraging e as T over <T>e. Understanding that would be beneficial if a new prefix syntax is to be considered.

matt-tingen avatar Aug 08 '19 17:08 matt-tingen

e as T is the only one that works in TSX contests, so it's easier to just universally recommend that

RyanCavanaugh avatar Aug 08 '19 17:08 RyanCavanaugh

Another use-case is being able to do richer excess property checking with helper types, without needing to keep the verbose helper type around:

type UnionKeys<T> = T extends unknown ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends unknown ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>

const check = <U>(x: U) => <T extends U extends T ? unknown : [U, 'not assignable to', T]>(): U => x;

type Foo = {
    a : number,
    b : number,
};
type Bar = {
    a : number,
    c : number,
};

export const obj = check({
    a : 0,
    b : 0,
    c : 0,
})<StrictUnion<Foo | Bar>>(); // error

jack-williams avatar Aug 12 '19 08:08 jack-williams

Such an operator could also help resolve situations where type narrowing on initialization introduces a type error:

type A = 1 | 2;
const one: A = 1;
[one].concat([2]) // error!

The proposed operator allows the programmer to explicitly specify the exact type without giving up on type safety. See #36530 for details.

fefrei avatar Jan 30 '20 15:01 fefrei

I'm having a big need for something like this because a lot of Redux / React reducer hook patterns suggest to create an initial state literal, and then construct the state's type from that initial state.

For example, this is what I'm currently doing:

const initItemState = {
// the stuff inside here isn't important, it's just for demonstration purposes
    count: number,
    items: [] as SomeItem[],
    submissionStatus: {
        isSubmitting: false,
        errorMessage: ""
    } as GenericStatusInterface
}

type ItemState = typeof initItemState;

export function Reducer(
  state: ItemState,
  action: (actionType: string)=>ItemState
): ItemState { ... some function here}

However, if I later change SomeItem or GenericStatusInterface, I will not get an error because I am using as T.

A small workaround that I've found that decreases legibility/increases verbosity but does give errors is doing this:

const initItems: SomeItem = [];
const initSubmissionStatus : GenericStatusInterface= {
    isSubmitting: false,
    errorMessage: ""
}
const initItemState = {
    count: number,
    items: initItems,
    submissionStatus: {
        isSubmitting: false,
        errorMessage: ""
    } as GenericStatusInterface
}

I've only been able to casually skim the comments above, so if there has been any better workarounds for this, please let me know.

w0nche0l avatar Apr 11 '20 03:04 w0nche0l

We ran into a situation like this a little while back.

We've got this type:

type Thing = {
    [key: string]: Thing | number
};

and this object:

const a = {
    foo: 4,
    bar: {
        a: 2,
        b: 3
    }
};

We want to assert that a has the structure of Thing, but without erasing the properties of a (that is, we would want a.c to result in a type error).

The solution we ended up using was

const makeThing = <T extends Thing>(x: T): T => {
    return x;
};
const a = makeThing({ ... });

It would be nice to have something like const a = { ... } is Thing instead.

AJGranowski avatar Apr 13 '20 23:04 AJGranowski

This would be helpful in situations like this with unions of promises of different types:

interface A { a: number }
interface B { b: number }

declare const p1: Promise<A>
declare const p2: Promise<B>

// This expression is not callable.
//   Each member of the union type '...' has signatures, but none of those signatures are
//   compatible with each other.
(Math.random() > 0.5 ? p1 : p2).then(() => {})

// Safe, but must use another variable
const safe: Promise<A | B> = Math.random() > 0.5 ? p1 : p2
safe.then(() => {})

// No extra variable/function required, but unsafe
;((Math.random() > 0.5 ? p1 : p2) as Promise<A | B>).then(() => {})
// Could fail at runtime
;((Math.random() > 0.5 ? p1 : p2) as Promise<A>).then(x => console.log(x.a.toFixed()))

cherryblossom000 avatar Oct 31 '20 00:10 cherryblossom000

I'm working on something where this would be very useful to have. I was hoping there would be a symbol to reference the type itself, like & or @ or : 🤷‍♂️. Just posting an example of what's in my head in case it helps:

type StateMachine = {
  startAt: keyof &.states,
  states: {
    [key: string]: State
  }
}

ff-jkrispel avatar Nov 13 '20 05:11 ff-jkrispel

@ff-jkrispel There's this, but that only works in interfaces. And I've used that quite a bit to do advanced type hackery with records without requiring spraying additional generic parameters everywhere.

dead-claudia avatar Nov 23 '20 05:11 dead-claudia

@DanielRosenwasser The is operator described above would respond to the issue that I raised #41715 (provided it can be used along the as const statement). You can close it.

I'll add my use case for the record 😀

I have developed a library that infers valid types from JSON schemas only through type computations, by making profit of the as const statement, generics and type recursions 👉 https://github.com/ThomasAribart/json-schema-to-ts

import { FromSchema } from "json-schema-to-ts";

const dogSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer" },
    hobbies: { type: "array", items: { type: "string" } },
  },
  required: ["name", "age"],
  additionalProperties: false,
} as const;

type Dog = FromSchema<typeof dogSchema>;
// => { name: string; age: number; hobbies?: string[] }

The as const statement is needed to keep typeof dogSchema as narrow (and thus parsable) as possible.

Currently, FromSchema will raise an error if typeof dogSchema doesn't extend DefinitelyTyped's JSON schema definitions. It's better than nothing, but it would be great to have the benefits of a type assignment (autocomplete, error highlighting etc...).

import { JSONSchema } from "json-schema-to-ts"; // <= Readonly type based on DefinitelyTyped

const invalidSchema = {
  type: "object",
  properties: {
    name: "string" // <= Error is raised
} as const is JSONSchema;

const validSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
  }
} as const is JSONSchema;

type ValidData = FromSchema<typeof validSchema> // <= Still works

ThomasAribart avatar Nov 30 '20 22:11 ThomasAribart

This would be very helpful. I'm currently using a helper function

function isType<T>(value: T): T {
  return value;
}

in my source code, but this obviously creates an unnecessary function call.

sschultze avatar Dec 29 '20 19:12 sschultze

Hi, I appear to have written a sister issue to this one #42138.

The way I see it, it feels to me this suggested operator might be built around the workaround rather than address the root issue at hand: that there exist currently untypable constructs in Typescript (i.e. variables that cannot be currently typed-checked without so called "utility-functions" like the one shown in the workarounds above).

Out of the top of my head it occurs to me that there are at least four scenarios of untypable constructs :

  • Objects
  • Arrays
  • Generics
  • Functions

I believe that these scenarios, are what you are trying to solve with this operator and that they could also be addressed with contextual types.

Proposals

These proposals all specify contextual types using the keyword infer used outside of conditional types. I will use string for all non-contextual types provided by the user.

Objects

// LHS, Infer keys types
type ValuesMustBeStrings = {[key: infer] :  string}
// RHS, Infer value types
type KeysMustBeStrings = {[key: string] :  infer}

This would be very useful for declaring collections objects with constrains that need to be followed. The two main work arounds for this are index types, or as const which are not meant to be used used for this use-case and have undesirable side-effects (e.g. forcing you to hardcode keys and values and making everything readonly respectively).

Arrays

// Infer value types
type LengthTwoTuple = [infer, infer]
type  FirstValueMustBeAString = [strings, …infer]

This would be very useful for tuple types, as the current way of typing an inferred tuple is through hacky typing-functions.

Generics

// Assume a type from a third party library with three generic argument A,B and C
const myArglessThing: TypeFromLibrary =  new Thing();
const myExplicitlyArglessThing: TypeFromLibrary<infer, infer, infer> = new Thing();
//Assume now that the default values are unsuitable and I don’t want override inference of the last two types.  
// Either because I don’t want to or can’t easily do so(say the default types for the the second two values are private)
const myThing: TypeFromLibrary<string, infer, infer> =  new Thing(’lets say this is the string value’);

Functions

type Both_inferred = infer => infer // this would be the explicit equivalent to not providing a type on declaration
type Lhs_inferred = infer => number // only the argument is inferred
type Rhs_inferred = ( arg: number ) => infer // only the return type is inferred

See: #42138 where I wrote extensively about this functions with contextual typings.

RodrigoRoaRodriguez avatar Jan 07 '21 17:01 RodrigoRoaRodriguez

@RodrigoRoaRodriguez I have read your comment twice, I don't have the feeling that it has anything to do with this issue. Perhaps you posted it at the wrong place.

sschultze avatar Jan 07 '21 18:01 sschultze

It is not only me. Others seem to think #42243 is related to #7481 (see #42243). While superficially the two issues might seem unrelated, they seek to solve the same problem.

Look at the my examples of function workarounds, and you will realize that they are all either variants of, or identical to:

function asType<T>(value: T) {
  return value;
};

In fact, just like in the third post in this thread, my own code example demo for #42243 was also state management in React with component actions.

The main difference between the two Github issues is that while #7481 suggests an operator:

// I know this is the workaround, but I could not find a proposal for how the operator syntax is supposed to look
export const ConnectedAsType = connect(undefined, asType<MyComponentActions>({
  selectSomething,
}))(MyComponent);

#42243 suggests a type as a solution:

const Actions: TypeWithFunctionInference = {
  selectSomething,
};

export const  ConnectedAsType = connect(undefined, actions)(MyComponent);

As you can see, both seek achieve the same result. #7481 and #42243 are just approaching a common problem from different angles and suggesting different syntax.

This is a complex issue and one that I understand it is difficult to explain, given how abstract and large it is. Please, do not hesitate to ask if you have any questions or would like a more in-depth explanation of what I am saying and why I am saying it.

RodrigoRoaRodriguez avatar Jan 07 '21 23:01 RodrigoRoaRodriguez

Looks like @ThomasAribart beat me to my own suggestion. That being said, if i may offer one suggestion on top of his - I think there's a big opportunity here to re-use the implements keyword rather than creating a new is operator:

interface JSONSchema { /* ... */ }
const validSchema = { /* ... */ } as const implements JSONSchema;

or even

interface JSONSchema1 { /* ... */ }
type JSONSchema2 = { /* ... */ }
const validSchema = { /* ... */ } as const implements JSONSchema1, JSONSchema2;

Forgive me now for scope-creeping, but if we entertain the idea of a generalized implements, this could be used in a much more powerful way with other variations of type declarations (see related suggestion):

// explicit
type ValidSchema implements JSONSchema1, JSONSchema2 = { /* ... */ }
type ValidSchema = { /* ... */ } implements JSONSchema1, JSONSchema2
interface ValidSchema implements JSONSchema1, JSONSchema2 { /* ... */ }

// inferred
const validSchema implements JSONSchema1, JSONSchema2 = someExpression
const validSchema = someExpression implements JSONSchema1, JSONSchema2

btoo avatar Feb 28 '21 05:02 btoo