Encountered TS type conversion cases

Encountered TS type conversion cases

Some manual type conversions in TypeScript, mainly for own use (x

Get the value of enum dynamically

This is a case I encountered before. Some keys are obtained from the backend, and enum is defined in ts, but an error will be reported saying that it is not the type of enum. The solution is to use as keyof typeof SomeEnum. In some complicated cases, it is also possible to directly convert enum to any:

enum SomeEnum {
    
    }

const randomKeyFromAPI = '';

const enumValue = SomeEnum[randomKeyFromAPI as keyof typeof SomeEnum];
// not preferable
const enumValue = (SomeEnum as any)[randomKeyFromAPI];

cycle object

The solution here is mainly Object.keys()the incompatibility between this and type/interface:

let objKeys = Object.keys(data) as Array<keyof MyType>;
// 上下只需要用一个就好了
objKeys.map((item: keyof MyType) => {
    
    
  return '';
});

Some keys are optional

The main problem to be solved is that when manipulating objects at the front end, some values ​​in the table are modifiable, while others are not (such as id, createdTime, etc.):

interface SomeType {
    
    
  prop1: string;
  prop2: string;
  prop3: string;
  propn: string;
}

type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> &
  Pick<T, TRequired>;

type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>;

let o: NewType = {
    
    
  prop1: '',
  prop2: '',
};

When looping, the current key is the common key of the two objects

There is probably a better solution to this...? But at present, this is a usable one.

Maybe it’s better to use all of them in this troublesome situation any(scratching one’s head

If it loops, I don’t know if there is a way to get the type of the current key...it seems impossible, because the type/interface is only available at compile time, but not at runtime, so it can only be used when the type after the transfer is reassigned any...

export const convertEntityToPlace = <T>(
  structure: Record<string, Partial<SomeStructure>>,
  data: T
) => {
    
    
  const convertedData: T = data;
  for (const key of Object.keys(structure)) {
    
    
    const toPlace = structure[key]?.toPlace ?? 0;
    if (toPlace > 0) {
    
    
      convertedData[key as keyof T] = ((data[key as keyof T] as number) /
        Math.pow(10, structure[key].toPlace as number)) as any;
    }
  }

  return convertedData;
};

reference

In fact, it is mainly found on stack overflow, but some cannot be found (...

Guess you like

Origin blog.csdn.net/weixin_42938619/article/details/132273049