Home > Software design >  Can the union type be the generic parameter?
Can the union type be the generic parameter?

Time:10-10

function fun3<T extends string>(arg: T) {
  return arg.length;
}

const aa = fun3<
    | "--text-color"
    | "--background-color"
    | "--border-radius"
    | "--border-width"
    | "--border-style"
    | "--border-color"
  >("--border-color");

I assign the fun3 generic

| "--text-color"
    | "--background-color"
    | "--border-radius"
    | "--border-width"
    | "--border-style"
    | "--border-color"

, but I think this is not the string type, why I can assign it to the function?

CodePudding user response:

enter image description here

It's allowed since that union of strings is assignable to string. See this diagram above. "a" is apart of string. That means we can give anything that expects a string, an "a". However, we cannot give it a 1 because 1 is not in the string circle.

You may use extends to check assignability, or use an assignment directly (but this tends to be more troublesome):

type Check01 = "a" | "b" extends string ? true : false;

const check01: string = null as unknown as "a" | "b";

Playground


Let's pretend that this is not the case for a moment. If there is no generic constraint, then what would you pass?

function myFunc<T>(arg: T) {

This simple doesn't make sense (why would you only be able to pass unknown?) and is not useful at all.


diagram source

  • Related