Aaronius / penpal

A promise-based library for securely communicating with iframes via postMessage.
MIT License
389 stars 56 forks source link

Allow generic types for `IConnectionObject` #22

Closed ahtcx closed 5 years ago

ahtcx commented 5 years ago

With generic types we can now have a strongly typed IConnectionObject promise. We can optionally define the types whilst calling connectToChild or connectToParent.

interface ParentMethods {
  multiply: (num1: number, num2: number) => number;
  divide: (num1: number, num2: number) => Promise<number>;
}

const parent = await Penpal.connectToParent<ParentMethods>(options).promise;

const a = await parent.multiply(2, 6);
const b = await parent.divide(12, 4);
const c = await parent.add(3, 1); // [ts] Property 'add' does not exist on type 'ParentMethods'

If no type is provided it will default to any which is the current value so nothing will break.

Aaronius commented 5 years ago

I don't know much about TypeScript, but I'll take your word for it. Thanks for the contribution!

Aaronius commented 5 years ago

Published in 3.0.4. Thanks again.

mike-north commented 5 years ago

These types don't work properly, and won't even compile by themselves. I'll submit some fixes w/ tests

Aaronius commented 5 years ago

Thanks @mike-north.

ahtcx commented 5 years ago

@mike-north How so? Everything is working on my end, with typescript@3.2.2. Sorry if this broke something...

mike-north commented 5 years ago

Everything is working on my end, with typescript@3.2.2. Sorry if this broke something...

Ambient types are really tricky to get right, since it's a set of constraints that must perfectly line up with the underlying code. Like anything, once you know how to test them, it's a lot easier to be confident around correctness.

If you're interested in learning more, here's the package we to test type declarations in DefinitelyTyped (all the @types/* npm packages) and here's an article I wrote to help people new to .d.ts files

https://medium.com/@mikenorth/guide-to-typescript-ambient-declarations-717ef6da6514