Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

TypeScript: Turning a generic string array into a union of string literals

I found that when I use a generic variadic, I can successfully coerce a function's input of strings into a Union of the literal values passed

declare function variadicGenericArray<Items extends string[]>(...items: Items): {[value in Items[number]: value}
const test = variadicGenericArray("One", "Two");
type testType = typeof Test; // {"One": "One", "Two": "Two"}

However when I try to extract these types using a normal array as the argument, then I don't get a union of literals.

declare function nonVariadicGenericArray<Items extends string[]>(items: Items): {[value in Items[number]: value}
const test = nonVariadicGenericArray(["One", "Two"]);
type testType = typeof Test; // {[x: string]: string}

What can I do to ensure that testType has the type {"One": "One", "Two": "Two"} and still have the function take in an array rather than variadic arguments?

An important note. I'm trying to write a function definition here, and the function is supposed to be generic, so I can't just declare type Values = "One" | "Two" or type Values = ["One", "Two"] as const and use those, since then the function would no longer be generic

question from:https://stackoverflow.com/questions/65894238/typescript-turning-a-generic-string-array-into-a-union-of-string-literals

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Played around a little and it looks like I can do this

declare function nonVariadicGenericArray<Items extends readonly string[]>(items: Items): {[value in Items[number]: value}
const test = nonVariadicGenericArray(["One", "Two"] as const);
type testType = typeof Test; // {"One": "One", "Two": "Two"}

Now I'll need to figure out which API is the better developer UX, but at least I have an answer now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...