Suggestion
π Search Terms
type-safe const assertions
β
Viability Checklist
My suggestion meets these guidelines:
β Suggestion
By allowing const assertions to accept a type, they can statically validate the type of the value during construction, thereby providing the benefit of both standard and const assertions at the same time:
literalExpression as const Type
<const Type>literalExpression
where literalExpression is the literal expression whose type is being derived and Type is the type against which the derived type is going to be checked for extends
π Motivating Example
type WeekDay = 'm' | 'tu' | 'w' | 'th' | 'f';
const mondayAndTuesday = ['m', 'tu'] as const WeekDay[]; // needs to not error
type ConstAssertion1 = typeof mondayAndTuesday extends WeekDay[] ? true : false; // true
type ConstAssertion2 = typeof mondayAndTuesday extends readonly ['m', 'tu'] ? true : false; // true
const mondayTuesdayAndSaturday = ['m', 'tu', 'sa'] as const WeekDay[]; // needs to error
This should also make it possible to allow autocomplete suggestions when literalExpression as const WeekDay[] is being written
π» Use Cases
I often find myself having to choose between using a standard type assertion and using a const assertion. Both offer important capabilities for static analysis:
- Standard: Assert that the
type of the value being constructed extends SomePreexistingType
- e.g.
type WeekDay = 'm' | 'tu' | 'w' | 'th' | 'f';
'sa' as WeekDay; // correctly errors
const: Prevent type-widening of the value being constructed
- e.g.
const weekDays = ['m', 'tu', 'w', 'th', 'f'] as const;
weekDays.filter(weekDay => weekDay === 'sa'); // correctly errors
However, there isn't a way to have them both (at least not without a runtime assertion function, it seems)
Suggestion
π Search Terms
type-safe const assertions
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
By allowing
constassertions to accept atype, they can statically validate the type of the value during construction, thereby providing the benefit of both standard andconstassertions at the same time:literalExpression as const Type<const Type>literalExpressionwhere
literalExpressionis the literal expression whose type is being derived andTypeis the type against which the derived type is going to be checked forextendsπ Motivating Example
This should also make it possible to allow autocomplete suggestions when
literalExpression as const WeekDay[]is being writtenπ» Use Cases
I often find myself having to choose between using a standard type assertion and using a
constassertion. Both offer important capabilities for static analysis:typeof the value being constructedextendsSomePreexistingTypeconst: Prevent type-widening of the value being constructedHowever, there isn't a way to have them both (at least not without a runtime assertion function, it seems)