The like
operator - type-checking without typing
#47834
Labels
Duplicate
An existing issue was already created
like
operator - type-checking without typing
#47834
Suggestion
A
like
operator should be introduced which occupies the same position in the AST of e.g.as
oras const
relative to the declaration of a value, but only introduces validation against a type (as if it was being assigned to that type) without changing the actual type of the value, especially without broadening it.🔍 Search Terms
Type-checking without Type-casting.
Inference-preserving type-check.
Type Validation
I have shared some examples for the suggestion below, but I probably just haven't found the right terms for what I'm looking for and it's a request which has already been considered. If this is the case I would like to find the issue and track the feature.
✅ Viability Checklist
This is deliberately designed to follow the existing type-erasure approach and introduces no new forms of checking, but just hints to the compiler some extra checking you would like to error on. In particular, you want all the typing of the existing assignment, but with the further type-checking of an additional type.
⭐ Suggestion
I suggest that a
like
operator is introduced which triggers the type-checking normally associated with assignment but which does no type-casting (e.g. the type actually assigned is not affected by addinglike MyType
).📃 Motivating Example
Given a type like this...
It might be used in scenarios such as this, ensuring that compile-time typechecking doesn't drive the creation of unnecessary runtime code...
Inline type-checking
Existing common pattern
Send back a JSON response in an express server (via an untyped method)
Workaround : unnecessary runtime assignment
Using
like
: avoids runtime assignment...and would raise errors for the following obvious cases...
Inference-preserving type-checking
Given the standard workaround we get unnecessary type-broadening
We can make sure the type has
msg
by usingas const
and use an extra throwaway runtime assignment in a block scope to do the validation, but it does nothing at runtime and is weird...This also introduces potential problems where there are no excess property checks, meaning this compiles when the developer probably doesn't want it to.
With the
like
operator, the item will be validated as aLogItem
but can still have the known literal types it gets fromas const
. It hasn't been unnecessarily broadened toLogItem
where msg is optional, simply as part of trying to validate its shape, andlike
will report on excess properties.This would compile and fulfil the requirements by using
like
And this would error on
stupid
as an excess property.Potentially order could matter, so that if
LogItem
does not accept readonly properties, you could reorder the operators, meaningLogItem
gets to do the validation before it gets typed to readonly.The text was updated successfully, but these errors were encountered: