Last active
April 6, 2022 10:36
-
-
Save ibhargav90/32982afd8c30d68fe8f921a4895161f0 to your computer and use it in GitHub Desktop.
TS tips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Entity = | |
| { | |
type: "user" | |
}| { | |
type: "post" | |
}| { | |
type: "comment" | |
}; | |
type EntityWithId = | { | |
type: "user", | |
userId: string | |
}| { | |
type: "post", | |
postId: string | |
}| { | |
type: "comment", | |
commentId: string | |
}; | |
const result: EntityWithId = { | |
type: "user", | |
userId: "1qaz" | |
} | |
// Add dynamic keys to union types | |
type NewEntityWithId = { | |
[EntityType in Entity["type"]]: { | |
type: EntityType | |
} & Record<`${EntityType}Id`, string> | |
}[Entity["type"]] | |
// const b: NewEntityWithId = { | |
// user: { | |
// type: "user" | |
// }, | |
// post: { | |
// type: "post" | |
// }, | |
// comment: { | |
// type: "comment" | |
// } | |
// } | |
const b: NewEntityWithId = { | |
type: "post", | |
postId: "adfsd" | |
} | |
console.log(b) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// object type to unions | |
export const fruitcounts = { | |
banana: 3, | |
apple: 4, | |
grapes:40, | |
jack:4 | |
} | |
type singleFruitCount = | |
| { | |
apple: number | |
} | |
| { | |
banana: number | |
}| { | |
grapes: number | |
}; | |
type FruitCounts = typeof fruitcounts; | |
type NewSingleFruitCount = { | |
[K in keyof FruitCounts]: { | |
[K2 in K]: number | |
} | |
}[keyof FruitCounts] | |
const singleFruitCount: NewSingleFruitCount = { | |
apple: 2 | |
} | |
console.log(singleFruitCount) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment