The EventBridgeEvent
interface found in "@types/aws-lambda"
is defined as:
export interface EventBridgeEvent<TDetailType extends string, TDetail>
Notice that TDetailType
extends the string
type. What's interesting to me is that I can define a variable as:
event: EventBridgeEvent<'stringLiteralFoo', Bar>
In order to prevent copying/pasting the string literal I tried to define it as a variable but then I am no longer able to use it as a type.
const stringLiteralFooVar = 'stringLiteralFoo'
event: EventBridgeEvent<stringLiteralFooVar, Bar>
The error I get is:
'stringLiteralFoo' refers to a value, but is being used as a type here. Did you mean 'typeof stringLiteralFoo'?
The full definition of the Event Bridge Event is
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;
}
So to find the detail-type
of a specific event I'm doing the following:
event: EventBridgeEvent<'stringLiteralFoo', Bar>
if (event['detail-type'] == 'stringLiteralFoo') {
// logic here
}
But I'd like to prevent copying/pasting the 'stringLiteralFoo'
literal.
Here is the minimal reproducible example:
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 {}
So my final question is, in the example above, how can I prevent copying and pasting the literal string; 'stringLiteralFoo'
?