LookUp
介绍
过在联合类型Cat | Dog
中通过指定公共属性type
的值来获取相应的类型。换句话说,在以下示例中,LookUp<Dog | Cat, 'dog'>
的结果应该是Dog
,LookUp<Dog | Cat, 'cat'>
的结果应该是Cat
。
例如
ts
interface Cat {type: 'cat'breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'}interface Dog {type: 'dog'breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'color: 'brown' | 'white' | 'black'}type MyDog = LookUp<Cat | Dog, 'dog'> // expected to be `Dog`
View on GitHubts
interface Cat {type: 'cat'breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'}interface Dog {type: 'dog'breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'color: 'brown' | 'white' | 'black'}type MyDog = LookUp<Cat | Dog, 'dog'> // expected to be `Dog`
起点
ts
/* _____________ Your Code Here _____________ */typeLookUp <U ,T > = any/* _____________ Test Cases _____________ */interfaceCat {type : 'cat'breeds : 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'}interfaceDog {type : 'dog'breeds : 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'color : 'brown' | 'white' | 'black'}typeAnimal =Cat |Dog typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <LookUp <Animal , 'dog'>,Dog >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <LookUp <Animal , 'cat'>,Cat >>,]
take the challengets
/* _____________ Your Code Here _____________ */typeLookUp <U ,T > = any/* _____________ Test Cases _____________ */interfaceCat {type : 'cat'breeds : 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'}interfaceDog {type : 'dog'breeds : 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'color : 'brown' | 'white' | 'black'}typeAnimal =Cat |Dog typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <LookUp <Animal , 'dog'>,Dog >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <LookUp <Animal , 'cat'>,Cat >>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typeLookUp <U ,T > =U extends {type :T } ?U : never;
ts
typeLookUp <U ,T > =U extends {type :T } ?U : never;