How can I assign a TypeScript type for event payloads for a class like EventEmitter?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I have a class that is just like Node's EventEmitter (it could even be the same class).
How do I type it in such a way that I can specify what the callback type is for each different event name?
For example, I'd like for even "foo"
to have a payload of type number
, and event "bar"
to have a payload of type string
, as in:
const emitter = /* get emitter from somewhere. And how would the type definition look like? */
emitter.on('foo', payload => {
/* type of payload is number, enforced by TypeScript */
testNumber('foo') // TS error, 'foo' is not a number
testNumber(payload) // it works, payload is a number
})
emitter.on('bar', payload => {
/* type of payload is string, enforced by TypeScript */
testString(5) // TS error, 5 is not a string
testString(payload) // it works, payload is a string
})
function testNumber( value: number ) {}
function testString( value: string ) {}
How would we define the EventEmitter declaration so that it is possible to define events and their types, and to then let users use those events with the correct type checking?
Maybe there's a way to define the type of EventEmitter such that when I create one I pass a type argument that contains all the expected types?
Is there a way to do it dynamically after creation?
typescript eventemitter
add a comment |
I have a class that is just like Node's EventEmitter (it could even be the same class).
How do I type it in such a way that I can specify what the callback type is for each different event name?
For example, I'd like for even "foo"
to have a payload of type number
, and event "bar"
to have a payload of type string
, as in:
const emitter = /* get emitter from somewhere. And how would the type definition look like? */
emitter.on('foo', payload => {
/* type of payload is number, enforced by TypeScript */
testNumber('foo') // TS error, 'foo' is not a number
testNumber(payload) // it works, payload is a number
})
emitter.on('bar', payload => {
/* type of payload is string, enforced by TypeScript */
testString(5) // TS error, 5 is not a string
testString(payload) // it works, payload is a string
})
function testNumber( value: number ) {}
function testString( value: string ) {}
How would we define the EventEmitter declaration so that it is possible to define events and their types, and to then let users use those events with the correct type checking?
Maybe there's a way to define the type of EventEmitter such that when I create one I pass a type argument that contains all the expected types?
Is there a way to do it dynamically after creation?
typescript eventemitter
add a comment |
I have a class that is just like Node's EventEmitter (it could even be the same class).
How do I type it in such a way that I can specify what the callback type is for each different event name?
For example, I'd like for even "foo"
to have a payload of type number
, and event "bar"
to have a payload of type string
, as in:
const emitter = /* get emitter from somewhere. And how would the type definition look like? */
emitter.on('foo', payload => {
/* type of payload is number, enforced by TypeScript */
testNumber('foo') // TS error, 'foo' is not a number
testNumber(payload) // it works, payload is a number
})
emitter.on('bar', payload => {
/* type of payload is string, enforced by TypeScript */
testString(5) // TS error, 5 is not a string
testString(payload) // it works, payload is a string
})
function testNumber( value: number ) {}
function testString( value: string ) {}
How would we define the EventEmitter declaration so that it is possible to define events and their types, and to then let users use those events with the correct type checking?
Maybe there's a way to define the type of EventEmitter such that when I create one I pass a type argument that contains all the expected types?
Is there a way to do it dynamically after creation?
typescript eventemitter
I have a class that is just like Node's EventEmitter (it could even be the same class).
How do I type it in such a way that I can specify what the callback type is for each different event name?
For example, I'd like for even "foo"
to have a payload of type number
, and event "bar"
to have a payload of type string
, as in:
const emitter = /* get emitter from somewhere. And how would the type definition look like? */
emitter.on('foo', payload => {
/* type of payload is number, enforced by TypeScript */
testNumber('foo') // TS error, 'foo' is not a number
testNumber(payload) // it works, payload is a number
})
emitter.on('bar', payload => {
/* type of payload is string, enforced by TypeScript */
testString(5) // TS error, 5 is not a string
testString(payload) // it works, payload is a string
})
function testNumber( value: number ) {}
function testString( value: string ) {}
How would we define the EventEmitter declaration so that it is possible to define events and their types, and to then let users use those events with the correct type checking?
Maybe there's a way to define the type of EventEmitter such that when I create one I pass a type argument that contains all the expected types?
Is there a way to do it dynamically after creation?
typescript eventemitter
typescript eventemitter
edited Nov 29 '18 at 1:44
trusktr
asked Nov 29 '18 at 1:20
trusktrtrusktr
17.6k31116168
17.6k31116168
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I'd start off with something like this:
interface Events {
foo: number;
}
interface EventEmitter<T> {
on<K extends keyof T>(s: K, listener: (v: T[K]) => void);
emit<K extends keyof T>(s: K, request: T[K]): any;
}
declare const emitter: EventEmitter<Events>;
emitter.on('foo', (payload) => {
console.log(payload);
});
emitter.emit('foo', 1);
Here's an example on TS Playground.
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set ofEvents
, and can only import theemitter
instance. Is it possible?
– trusktr
Nov 29 '18 at 1:36
What doesK extends keyof T
mean exactly?
– trusktr
Nov 29 '18 at 1:36
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
|
show 2 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53530510%2fhow-can-i-assign-a-typescript-type-for-event-payloads-for-a-class-like-eventemit%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I'd start off with something like this:
interface Events {
foo: number;
}
interface EventEmitter<T> {
on<K extends keyof T>(s: K, listener: (v: T[K]) => void);
emit<K extends keyof T>(s: K, request: T[K]): any;
}
declare const emitter: EventEmitter<Events>;
emitter.on('foo', (payload) => {
console.log(payload);
});
emitter.emit('foo', 1);
Here's an example on TS Playground.
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set ofEvents
, and can only import theemitter
instance. Is it possible?
– trusktr
Nov 29 '18 at 1:36
What doesK extends keyof T
mean exactly?
– trusktr
Nov 29 '18 at 1:36
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
|
show 2 more comments
I'd start off with something like this:
interface Events {
foo: number;
}
interface EventEmitter<T> {
on<K extends keyof T>(s: K, listener: (v: T[K]) => void);
emit<K extends keyof T>(s: K, request: T[K]): any;
}
declare const emitter: EventEmitter<Events>;
emitter.on('foo', (payload) => {
console.log(payload);
});
emitter.emit('foo', 1);
Here's an example on TS Playground.
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set ofEvents
, and can only import theemitter
instance. Is it possible?
– trusktr
Nov 29 '18 at 1:36
What doesK extends keyof T
mean exactly?
– trusktr
Nov 29 '18 at 1:36
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
|
show 2 more comments
I'd start off with something like this:
interface Events {
foo: number;
}
interface EventEmitter<T> {
on<K extends keyof T>(s: K, listener: (v: T[K]) => void);
emit<K extends keyof T>(s: K, request: T[K]): any;
}
declare const emitter: EventEmitter<Events>;
emitter.on('foo', (payload) => {
console.log(payload);
});
emitter.emit('foo', 1);
Here's an example on TS Playground.
I'd start off with something like this:
interface Events {
foo: number;
}
interface EventEmitter<T> {
on<K extends keyof T>(s: K, listener: (v: T[K]) => void);
emit<K extends keyof T>(s: K, request: T[K]): any;
}
declare const emitter: EventEmitter<Events>;
emitter.on('foo', (payload) => {
console.log(payload);
});
emitter.emit('foo', 1);
Here's an example on TS Playground.
edited Nov 29 '18 at 1:49
trusktr
17.6k31116168
17.6k31116168
answered Nov 29 '18 at 1:24
fuzzfuzz
15.8k17109187
15.8k17109187
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set ofEvents
, and can only import theemitter
instance. Is it possible?
– trusktr
Nov 29 '18 at 1:36
What doesK extends keyof T
mean exactly?
– trusktr
Nov 29 '18 at 1:36
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
|
show 2 more comments
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set ofEvents
, and can only import theemitter
instance. Is it possible?
– trusktr
Nov 29 '18 at 1:36
What doesK extends keyof T
mean exactly?
– trusktr
Nov 29 '18 at 1:36
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
Awesome! The mapped types are hard to grok, but this is helping me get there. Thanks!
– trusktr
Nov 29 '18 at 1:32
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
@trusktr Glad I could help.
– fuzz
Nov 29 '18 at 1:34
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set of
Events
, and can only import the emitter
instance. Is it possible?– trusktr
Nov 29 '18 at 1:36
What if the emitter instance is imported from a module, and I'd like to add a new event and payload type to it? Basically I don't have access to a predefined set of
Events
, and can only import the emitter
instance. Is it possible?– trusktr
Nov 29 '18 at 1:36
What does
K extends keyof T
mean exactly?– trusktr
Nov 29 '18 at 1:36
What does
K extends keyof T
mean exactly?– trusktr
Nov 29 '18 at 1:36
1
1
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
@trusktr It's probably best to ask a separate question on here.
– fuzz
Nov 29 '18 at 1:49
|
show 2 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53530510%2fhow-can-i-assign-a-typescript-type-for-event-payloads-for-a-class-like-eventemit%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown