microsoft / microsoft/TypeScript

Suggestion: Reference expression type during cast

Open
#37,729 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

cast reference expression type

Suggestion

I would like to be able to reference original type of the expression during cast.
For example:

const o = {
    x: { a: 1 } as typeof & { b?: number }
}

// type of o.x is now { a: number; b?: number }

I am not attached to typeof syntax here, can be anything that makes sense.

Use Cases

  1. Defining optional properties without actually initializing them.
    Current approach would require me to do something like:
const o = {
    x: { a: 1 } as { a: number; b?: number }
}

which is unweildy and repeats all the properties.
It is possible to do through a function, but it has an overhead and is complicated due to partial generics:

function extend<T>(T data) {
    return <TExtra>() => data as T & TExtra;
}

const o = {
    x: extend({ a: 1 })<{ b?: number }>()
}
  1. Adding indexers to object literals:
function map1(key: string) {
    return { a: 1, b: 2 }[key] || 3; // does not work due to https://github.com/microsoft/TypeScript/issues/14951
}

function map2(key: string) {
    return ({ a: 1, b: 2 } as { [key: string]: typeof[keyof typeof]|undefined })[key] || 3;
}

Examples

See use cases.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file, test, or entry point is named in the issue. Start by reviewing the proposed cast syntax and both use cases, then determine the type-system and syntax design needed; done would require an accepted approach and corresponding implementation scope.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.