Best Practices for Dynamically Generating Values in Literal Type Declaration

Asked 1 years ago, Updated 1 years ago, 62 views

Thank you for your help.

I'd like to ask you about the best practices for dynamically generating values when using literal type in TypeScript.

typevalueType='foo_1'|'foo_2';

const prefix=(value:string):string=>{
    const prefix = 'foo';
    return`${prefix}_${value}`;
}

const process=():valueType=>{
    if(/* omitted*/){
        return prefix ('1');
    } else{
        return prefix ('2');
    }
}

For example, if there is a code like this, the prefix is dynamically generated because it could change in the future.
Naturally, the following error will be printed in the return statement:

 type 'string' cannot be assigned to type 'valueType'.ts(2322)
const process=():valueType=>{
    if(/* omitted*/){
        return prefix('1') as 'foo_1';
    } else{
        return prefix('2') as 'foo_2';
    }
}

It's obviously useless, and it's better to write return'foo_1' from the beginning as it needs to be fixed if the prefix changes anyway.
→ Is it still better to specify the type explicitly?

In the first place, stop the literal type and leave it to type reasoning.
→ However, the possibility of anything other than foo_1 and foo_2 being included is zero, and if possible, I would like to tie it in literal form instead of string type.

I was an amateur for about a week in TypeScript, and I could hardly think of the best way to do it.
Isn't it possible to do it with generic?I tried and tried, but I still don't know if this is possible at the basic level of TypeScript.

  • Get rid of literal types and type inference is sufficient
  • Dynamic generation (prefixing) should stop
  • Can/Cannot do with generic type

I would appreciate it if I could ask my seniors about various knowledge.
I apologize for the inconvenience, but I appreciate your cooperation.

typescript

2022-09-30 19:54

1 Answers

I didn't understand what you wanted to do, but I think Template Literal Types is available.

typePrefix="foo";
type Postfix="1"|"2";
typeValueType=`${Prefix}_${Postfix}`;

const prefix=(value:Postfix): ValueType=>{
  const prefix = "foo";
  return`${prefix}_${value}`;
};

const process=(i:number): ValueType=>{
  if(i>0){
    return prefix ("1");
  } else{
    return prefix ("2");
  }
};

console.log(process(10)); // "foo_1"
console.log(process(-10)); // "foo_2"

(Playground)


2022-09-30 19:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.