microsoft / microsoft/TypeScript
Allow type assertions to consider typed index signatures
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
interface, index, signature, typed, assertion, conversion, partial,
Suggestion
Currently type assertions do not seem to respect typed index signatures [key: string]: any; in interfaces or test for compatibility before attempting to convert.
I am proposing that type assertions would be able to convert this situation without error:
interface Test {
a: string;
b?: string;
[key: string]: any;
}
const a = {b: 'b', c: 3 } as Test;
Use Cases
Currently to work around this I need to first create an intermediate variable that is typed as a Partial before making the assertion. I would prefer to just make the assertion.
Examples
This example above will error because {b: 'b', c: 3 } is missing property a
interface Test {
a: string;
b?: string;
[key: string]: any;
}
const a = {b: 'b', c: 3 } as Test;
If I remove c: 3 from the object then there is no error and a is no longer required:
interface Test {
a: string;
b?: string;
[key: string]: any;
}
const a = {b: 'b' } as Test;
Currently to workaround this an intermediate typed value can be used so the subtype is already confirmed before the assertion:
interface Test {
a: string;
b?: string;
[key: string]: any;
}
const test: Partial<Test> = { b: 'b', c: 3 };
const a = test as Test
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the linked Playground examples, especially the assertion involving a typed index signature and an extra property. Start by locating TypeScript's type-assertion compatibility checks and their regression tests; done means the proposed assertion succeeds while incompatible assertions continue to be rejected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100