英文:
Why does inferring the first tuple value from string[] lose it's type?
问题
When inferring the first tuple value from a string array, it seems like TypeScript loses the information that the inferred value must be a string. Why is the type lost?
type Test<T extends string> = true;
// Head should be known to be a string since T is string[]
type Example<T extends string[]> = T extends [infer Head, ...infer Tail]
? // Type 'Head' does not satisfy the constraint 'string'.
Test<Head>
: never;
I know I can solve the issue by using infer Head extends string
instead of infer Head
, but I don't understand why it's necessary. Is there some scenario I'm missing where Head
could be something other than a string
?
英文:
When inferring first tuple value from string array, it seems like TypeScript loses the information that the inferred value must be string. Why is the type lost?
type Test<T extends string> = true;
// Head should be known to be string since T is string[]
type Example<T extends string[]> = T extends [infer Head, ...infer Tail]
? // Type 'Head' does not satisfy the constraint 'string'.
Test<Head>
: never;
I know I can solve the issue by doing infer Head extends string
instead of infer Head
, but I don't understand why it's necessary. Is there some scenario I'm missing where Head
could be something else than string
?
答案1
得分: 1
You're not really missing anything; the type of Head
will always be assignable to string
in your example, but the compiler just doesn't see it.
There is an open feature request at microsoft/TypeScript#51108 to use information from generic constraints to further narrow the type of type parameters infer
red in conditional types. If you want to see this implemented, it wouldn't hurt to give that issue a 👍 and possibly describe your use case if it's novel and compelling. It probably wouldn't help much, but it wouldn't hurt.
Until and unless the feature is implemented, you'll have to work around it. The easiest workaround is probably to use a redundant extends
constraint on infer
red type parameters, as you mentioned.
英文:
You're not really missing anything; the type of Head
will always be assignable to string
in your example, but the compiler just doesn't see it.
There is an open feature request at microsoft/TypeScript#51108 to use information from generic constraints to further narrow the type of type parameters infer
red in conditional types. If you want to see this implemented, it wouldn't hurt to give that issue a 👍 and possibly describe your use case if it's novel and compelling. It probably wouldn't help much, but it wouldn't hurt.
Until and unless the feature is implemented, you'll have to work around it. The easiest workaround is probably to use a redundant extends
constraint on infer
red type parameters, as you mentioned.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论