簡體   English   中英

從聯合類型創建的Typescript合並映射類型

[英]Typescript merge mapped type created from union type

我正在嘗試從鍵的聯合類型創建映射類型。 為了有一個最小的例子,這些類型只是映射到它們自己。 以下通用返回預期結果

type Foo<Bar extends string> = {[name in Bar]: name}
type test = Foo<'test1' | 'test2'> //test = {test1: 'test1', test2: 'test2'}

但是,我想刪除字符串約束,如果Bar不是字符串,則返回undefined 我以以下方式做到了

type Foo<Bar> = Bar extends string ? {[name in Bar]: name} : undefined
type test = Foo<'test1' | 'test2'>
//expected result: test = {test1: 'test1', test2: 'test2'}
//actual result: test = {test1: 'test1'} | {test2: 'test2'}

test現在是聯合類型,而不是簡單的映射類型。

這是打字稿中的預期行為,還是我應該提交錯誤報告? 並且有什么方法可以得到我想要的行為嗎?

附注:如果可以提供幫助,我正在嘗試解決此問題

是的,這是預期的行為,它通常是有用的功能,稱為分布式條件類型

但是有時候,就像您的示例一樣,它會妨礙您的工作。 解決方法是在條件測試中使用 Bar類型參數時將其包裝在[]

type Foo1<Bar extends string> = {[name in Bar]: name}
type test1 = Foo1<'test1' | 'test2'> //test1 = {test1: 'test1', test2: 'test2'}

type Foo2<Bar> = [Bar] extends [string] ? {[name in Bar]: name} : undefined;
type test2 = Foo2<'test1' | 'test2'> //test2 = {test1: 'test1', test2: 'test2'}
type test3 = Foo2<1>; // undefined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM