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, names
is 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"'.
标签:5.0,Typescript,const,string,Alice,readonly,names,type
From: https://www.cnblogs.com/Answer1215/p/17076228.html