The EventBridgeEvent
interface in the "@types/aws-lambda"
package is defined as:
export interface EventBridgeEvent<TDetailType extends string, TDetail>
It's worth noting that TDetailType
extends the string
type. An interesting aspect is the ability to define a variable like this:
event: EventBridgeEvent<'stringLiteralFoo', Bar>
I attempted to define the string literal as a variable to avoid copy/pasting, but then I couldn't use it as a type.
const stringLiteralFooVar = 'stringLiteralFoo'
event: EventBridgeEvent<stringLiteralFooVar, Bar>
This resulted in the error:
'stringLiteralFoo' refers to a value, but is being used as a type here. Did you mean 'typeof stringLiteralFoo'?
The complete definition of the Event Bridge Event is as follows:
export interface EventBridgeEvent<TDetailType extends string, TDetail> {
id: string;
version: string;
account: string;
time: string;
region: string;
resources: string[];
source: string;
'detail-type': TDetailType;
detail: TDetail;
'replay-name'?: string;
}
To determine the detail-type
of an event, I'm using the following approach:
event: EventBridgeEvent<'stringLiteralFoo', Bar>
if (event['detail-type'] == 'stringLiteralFoo') {
// logic here
}
However, my goal is to avoid directly copying and pasting the 'stringLiteralFoo'
literal.
Here is a simple example to reproduce the issue:
export interface EventBridgeEvent<TDetailType extends string, TDetail> {
'detail-type': TDetailType;
detail: TDetail;
}
const event: EventBridgeEvent<'Foo1' | 'Foo2', Bar> = {
'detail-type': 'Foo1',
detail: {}, // of type Bar
}
if (event['detail-type'] == 'Foo1') {
// logic here
}
interface Bar {}
Therefore, my final question remains: How can I avoid copying and pasting the literal string 'stringLiteralFoo'
in the above example?