Last active
October 13, 2022 09:12
-
-
Save Hashbrown777/4c6eeff85dfbea54374f1da2d065b1d3 to your computer and use it in GitHub Desktop.
[a reason for private methods on the interface](https://stackoverflow.com/questions/37791947/how-to-define-a-private-property-when-implementing-an-interface-in-typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {Worker, TransferListItem, MessagePort, parentPort} from 'worker_threads'; | |
| interface MessagePair<T extends any, U extends any> { | |
| //THESE SHOULD BE PRIVATE | |
| //only present in the interface as a contract BETWEEN APPLICABLE (parameterised) parties | |
| //not ALL PUBLIC PARTIES | |
| //as they should use the IMPLEMENTATION'S EXPOSED METHODS | |
| message :(value :T) => void; | |
| postMessage :( | |
| value :U extends MessagePair<infer V, this> ? V : never, | |
| transferList ?:TransferListItem[] | |
| ) => void; | |
| } | |
| type Message<T> = T extends {message :(value :infer U) => void} ? U : never; | |
| //bob accepts strings from steve | |
| class Bob implements MessagePair<string[], Steve> { | |
| message = (strings :string[]) => { | |
| console.log(strings.join(' ')); | |
| }; | |
| postMessage :( | |
| steves :Message<Steve>, | |
| ports ?:TransferListItem[] | |
| ) => void; | |
| constructor(port :Worker) { | |
| //with the contract satisfied, this is safe | |
| this.postMessage = (...args :[any, any]) => { port.postMessage(...args) }; | |
| port.on('message', this.message); | |
| } | |
| //PUBLIC | |
| tellSteveThisPlease(some :number, numbers :number) { | |
| if (some > numbers) | |
| throw new Error('I don\'t trust like that'); | |
| this.postMessage([some, numbers]); | |
| } | |
| } | |
| //steve accepts numbers from bob | |
| class Steve implements MessagePair<number[], Bob> { | |
| message = (strings :number[]) => { | |
| this.postMessage(['yo', 'thanks']); | |
| }; | |
| postMessage :( | |
| bobs :Message<Bob>, | |
| ports ?:TransferListItem[] | |
| ) => void; | |
| constructor(port :MessagePort) { | |
| //with the contract satisfied, this is safe | |
| this.postMessage = (...args :[any, any]) => { port.postMessage(...args) }; | |
| port.on('message', this.message); | |
| } | |
| } | |
| //you shouldn't be able to send messages to steve/bob YOURSELF | |
| //they should be PRIVATE and you should have to ASK steve/bob to do so on your behalf | |
| //(if that's your IMPLEMENTATION) | |
| //parent | |
| (new Bob(new Worker(''))).tellSteveThisPlease(1, 2); | |
| //worker | |
| new Steve(parentPort!); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TypeScript Playground