sparebytes / typesmith Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
Hi.
Two questions:
(1) In all examples, the type is first defined as a named interface (or a type) and only then its name is passed to assertTypeFn:
interface Person {
name: string;
}
const assertPerson = assertTypeFn<Person>();
assertPerson(json).unwrap();
Is it intentional that it doesn't work with anonymous types?
const assertPerson = assertTypeFn<{ name: string; }>(); // <-- does not work
assertPerson(json).unwrap();
(2) I haven't found any way to pass the type via a generic parameter to some library function:
// json-request.ts
export async function jsonRequest<TRes>(url: string) {
const json = await fetch(url); // do some more magic there too, like logging
const asserter = assertTypeFn<TRes>();
return asserter(json).unwrap(); // <-- does not work
}
// some-file.ts
import { jsonRequest } from "json-request";
...
const res = await jsonRequest<{
name: string;
age?: number;
}>("https://example.com");
// I want res here to be (a) strongly typed and (b) validated at run-time
Probably it's expected, because TS transformer works locally and doesn't trace the callers. My question here is - how do I express something similar to this? Because the above syntax (some-file.ts) is basically the essence of what's needed in 99% of the cases... especially in the code which sends lots of different requests, and each request is mentioned there only once (so it makes no sense to create a named type for its response structure).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.