#Override types of module with another module

5 messages · Page 1 of 1 (latest)

vapid glade
#

I'm trying to do something but unsure how. To summarise I am wanting to override the types of everything exported from a "module" using a separate "module".
I am wanting three modules, one for the runtime, two for overriding the types of the first (for uses in different environments, the runtime module will handle the environment itself).

Can I do something like this?

// method.ts
export function method(value: unknown) {
  if (typeof value === 'string') return 'string';
  else if (typeof value === 'number') return 'number';
  else return 'unknown';
}
// number.d.ts
declare module './method' {
  declare function method(value: number): string;
}
// string.d.ts
declare module './method' {
  declare function method(value: string): string;
}
// index.ts
import { method } from './method';
import './number';

method('42'); // <- i want this to error
// ^? method(value: unknown): ...
// im wanting its signature to be method(value: number): ...
eternal orchid
#

This seems like an odd setup, what's the goal with this?

#

My first impression is that you should simply have ./string/method and ./number/method, each exporting their own methods with their own types, and consumer just import whichever they need. Especially because the method in your original example is already basically just writing it twice by duplicating the code for both versions on top of the runtime type check.

vapid glade
# eternal orchid This seems like an odd setup, what's the goal with this?

I'm making an API wrapper NPM package that I want to work on both server and serverless. However, on the server it will use WebSockets, which aren't available on serverless (that will use just plain http). The simplest option is to just create two packages for each environment, however there is already a lot code so I would like to try and combine them into a single runtime package, then use different type packages depending on the environment (server uses classes, serverless uses raw api objects).

// on server
import { Client } from '@org/core';
import '@org/gateway-types';
const client = new Client();

const post = await client.posts.fetch('abc');
//     ^? Post
await post.comment('xyz');
// on serverless
import { Client } from '@org/core';
import '@org/http-types';
const client = new Client();

const post = await client.posts.fetch('abc');
//     ^? { id: 'abc', content: 'xyz' }
client.posts.comment('abc', 'xyz');

||(not actually how my code works, just an example)||

eternal orchid