简体   繁体   中英

Typescript: Infer exact values from dynamically created object

Is there a way to infer the exact values from an object thats dynamically created with a helper function.

The values of the object will always be inferred as type string, but I would like to have their exact value, like my attempt at casting on the SIGN_IN declaration.

const createAsyncActionTypes = (label: string) => ({
  REQUEST: `${label}_${'SUCCESS'}`,
  SUCCESS: `${label}_${'SUCCESS'}`,
  ERROR: `${label}_${'ERROR'}`,
  CANCELLED: `${label}_${'CANCELLED'}`,
});

const SIGN_OUT = createAsyncActionTypes('SIGN_OUT');

const SIGN_IN: {
  REQUEST: 'SIGN_IN_REQUEST';
  SUCCESS: 'SIGN_IN_SUCCESS';
  ERROR: 'SIGN_IN_ERROR';
  CANCELLED: 'SIGN_IN_CANCELLED';
} = createAsyncActionTypes('SIGN_IN');

No, that's not possible.

You could cast the individual values to their related types, but that would defeat the point of dynamically creating the object:

在此输入图像描述

Typescript does not support "dynamic typing" like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM