#Is there a more elegant way to implement complex type guarding?

11 messages · Page 1 of 1 (latest)

blissful capeBOT
#
farad314#0

Preview:```ts
declare function isObject(obj: unknown): obj is object;
declare function isArrayLike<T>(obj: object, guard?: (element: unknown) => element is T): obj is ArrayLike<T>;

declare const valid: unique symbol;
declare type SpecialArrayLike<T> = ArrayLike<T> & { [valid]: true };
...```

mellow turret
#

Just like here, I wrote a lot of type guards to make typescript infer the correct type of obj, but still couldn't complete the check.
This obj may come from JS, so it needs to be carefully checked. I hope typescript can play a role somewhere and remind me if I missed checking any details of the interface

#

I don't want my code to be passed in with unacceptable data under any circumstances

#

like console

#

It should throw something to prevent unpredictable behaviors

#

I don't want to just implement a guard without typescript's help and "Claiming that obj correctly implements the interface i need"

#

That sounds very unreliable, especially once the interface changes, I may forget to update those guards

#

I know there are already some packages that can generate guards based on interfaces, but I have a lot of data like Integer or SpecialArrayLike in Demo that cannot be 100% accurately constrained by interfaces

#

I need some help to implement these guards myself

#

BTW, I have implemented some decorator like @final to ensure that some class methods are not overwritten, but they will report errors when running. Is there any way to make VS Code directly point out these errors?

atomic sundial
#

This is typically handled by validation libraries like Zod, Valibot, TypeBox, etc.