zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript 5.0] const Type Parameters with readonly

typescript with type const 5.0 parameters readonly
2023-09-14 08:59:11 时间

https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#exhaustive-switch-case-completions

 

In the example code:

type HasNames = { names: readonly string[] };
function getNamesExactly<T extends HasNames>(arg: T): T["names"] {
    return arg.names;
}

// Inferred type: string[]
const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"]}) ;

Before TS 5.0, namesis string[]. 

 

 

There was a way to handle in this case as const

// Correctly gets what we wanted:
//    readonly ["Alice", "Bob", "Eve"]
const names2 = getNamesExactly({ names: ["Alice", "Bob", "Eve"]} as const);

with as const, we need to make sure it is {names: readonly string[]} instead of {readonly names: string[]}, the string[] has to ben readonly, in order to infer the string literl type.

 

Typescript 5.0

We can use const in generic type, to acheive the effect as as const

<const T extends HasNames>
type HasNames = { names: readonly string[] }; //readonly here is important
function getNamesExactly<const T extends HasNames>(arg: T): T["names"] {
    return arg.names;
}

// Correctly gets what we wanted:
//    readonly ["Alice", "Bob", "Eve"]
const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"]}) ;

 

const Type parameters has to be used within the function call

Works

declare function fnGood<const T extends readonly string[]>(args: T): void;

// T is readonly ["a", "b", "c"]
fnGood(["a", "b" ,"c"]);

 

Not working

declare function fnGood<const T extends readonly string[]>(args: T): void;

const arr = ["a", "b" ,"c"]
// T is string[]
fnGood(arr);

 

 

---

Another example;

const routes = <const T extends string>(routes: T[]) => {
  const addRedirect = (from: T, to: T) => {}

  return {
    addRedirect
  }
}

const router = routes(["/users", "/posts", "/admin/users"])

router.addRedirect("/admin/users", "wef") // error: Argument of type '"wef"' is not assignable to parameter of type '"/users" | "/posts" | "/admin/users"'.