Skip to content

Instantly share code, notes, and snippets.

@ibhargav90
Last active April 6, 2022 10:36
Show Gist options
  • Save ibhargav90/32982afd8c30d68fe8f921a4895161f0 to your computer and use it in GitHub Desktop.
Save ibhargav90/32982afd8c30d68fe8f921a4895161f0 to your computer and use it in GitHub Desktop.
TS tips
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)
// 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