Closed
Description
openedon Jul 29, 2018
Search Terms
type erase assert validat assign
Suggestion
Recently I've been using a construct like the following in order to validate structures against a determinate type while still keeping their inferred type:
const validateType = <Requirement>() => <T extends Requirement>(i: T) => i
const aFunctionRecord = validateType<Record<string, Function>>() => ({
hello: (world: string) => { ... },
typescript: (cool: number) => { ... }
})
//aFunctionRecord retains its inferred type and will error if does not confirm the requirement
Oh, and this sometimes even infers parameters for functions, saving the need for some type annotations.
This is different from writing something like
const anotherFunctionRecord: Record<string, Function> = { ... }
//the inferred type is "lost"
While validateType
works great, it feels a bit hacky, since we need to create a "concrete" JS function in order to achieve that. It would be great if that type of check could be achieved just with type annotations. Example:
const aFunctionRecord : * extends Record<string, Function> = { ... }
//or
const aFunctionRecord = { ... } extends Record<string, Function>
I have used extends
in the example here since it's an already existing keyword, if you come up with a better idea...
thanks!
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. new expression-level syntax)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment