Skip to content
This repository has been archived by the owner on Apr 8, 2022. It is now read-only.

How to use in a library, how to use inline defined types? #1

Open
dko-slapdash opened this issue Nov 17, 2019 · 0 comments
Open

How to use in a library, how to use inline defined types? #1

dko-slapdash opened this issue Nov 17, 2019 · 0 comments

Comments

@dko-slapdash
Copy link

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).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant