use dynamic value for emit event name when emits are defined using typescript

I’m an experienced Vue dev but I’m new to typescript and by new I mean I’ve started 3 days ago with it.

I have a vue component that recules a list of request as a prop called ‘requestedTokens’ that is an object of future requests for each i need to fetch some auth tokens from the backend.

I’m calling this object of requests actions and here is an example of a request action that is using the type ‘NestedRequestProp’:

{
    store: {
        url: 'http://some-url',
        method: 'post',
        fields: {}
    {
}

These are my type declarations:

const Actions = ['index', 'show', 'create', 'store', 'edit', 'update', 'destroy', 'restore'] as const;
const ActionErrors = ['errorIndex', 'errorShow', 'errorCreate', 'errorStore', 'errorEdit', 'errorUpdate', 'errorDestroy', 'errorRestore'] as const;
const ActionListeners = ['onIndex', 'onShow', 'onCreate', 'onStore', 'onEdit', 'onUpdate', 'onDestroy', 'onRestore'] as const;
const ActionErrorListeners = ['onErrorIndex', 'onErrorShow', 'onErrorCreate', 'onErrorStore', 'onErrorEdit', 'onErrorUpdate', 'onErrorDestroy', 'onErrorRestore'] as const;


type RequestProp<FieldsType = object> = {
    url: string
    method: Method
    fields?: FieldsType
};

type NestedRequestProp<FieldsType = object> = {
    [key in RequestAction]: RequestProp<FieldsType>;
};

I also have some emits defined:

type Emit = {
    [key in RequestAction]: [value?: object];
} & {
    [key in RequestActionError]: [value: AxiosError<RequestErrorResponse<any>>]
} & {
    canceled: [value: any|undefined]
};

const emit = defineEmits<Emit>();

As you can see the event name are the RequestActons and the RequestActions with the string “Error” appended (EX.: ‘store’ or ‘storeError’).

Here is the success function that is being called with the response from the backend.

const success = async ({ status, data, wrapper }: {
    status: number;
    data: {
        token: Token;
    };
    wrapper: typeof FormWrapper;
}) => {
    if (status !== 201) return;

    for (const key of Object.keys(data.token)) {
        const listener = `on${capitalize(key)}` as RequestActionListener;
        const errorListener = `on${capitalize(key)}Error` as RequestActionListener;

        if (!!props[listener]) {
            processing.value = true;
            const { url, method, fields = {}} = props.requestedTokens[key as RequestAction];
            const [response, error] = await ApiCaller.requestWithError(url, method, fields, {
                headers: {
                    [auth.authorizationKey]: data.token[key as RequestAction],
                }
            });

            if (response && key in Actions) emit(key, response);
            else if (error && !!props[errorListener]) emit((`${key}Error` as RequestActionError), error);

            processing.value = false;
        }
    }

    wrapper.cancel();

    if (tokens.value) tokens.value = {
        key: auth.authorizationKey,
        token: data.token,
    };
};

My problem is with this part of it:

if (response && key in Actions) emit(key, response);
            else if (error && !!props[errorListener]) emit((`${key}Error` as RequestActionError), error);

I’m getting these two errors in vscode:

No overload matches this call.
The last overload gave the following error.
Argument of type ‘string’ is not assignable to parameter of type ‘”canceled”‘.ts-plugin(2769)
runtime-core.d.ts(229, 21): The last overload is declared here.
const key: string

And

No overload matches this call.
The last overload gave the following error.
Argument of type ‘”errorIndex” | “errorShow” | “errorCreate” | “errorStore” | “errorEdit” | “errorUpdate” | “errorDestroy” | “errorRestore”‘ is not assignable to parameter of type ‘”canceled”‘.
Type ‘”errorIndex”‘ is not assignable to type ‘”canceled”‘.ts-plugin(2769)
runtime-core.d.ts(229, 21): The last overload is declared here.
const key: string

I’ve tried to cast key as ActionRequest.

I’ve tried to define separate const for successEvent, errorEvent and type cast them with the respective types.

I’ve tried inline type assertion.

Whatever I do I’m getting red underlines under the event names.

Any help with be very appreciated.

8

I figured out. For anyone else having this problem the solution is to use the other vue syntax for defining emits.

Here is my solution:

const emit = defineEmits<{
    (e: RequestAction, value: any): void
    (e: RequestActionError, value: AxiosError<RequestErrorResponse<any>>): void
    (e: 'canceled', value?: any): void
}>();

I hope this help anyone having this problem.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật