Skip to content

Instantly share code, notes, and snippets.

@piyu-sh
Created August 28, 2020 08:59
Show Gist options
  • Save piyu-sh/b1e5de1ed8d789732c1d6135851e0152 to your computer and use it in GitHub Desktop.
Save piyu-sh/b1e5de1ed8d789732c1d6135851e0152 to your computer and use it in GitHub Desktop.
Useful Typescript types
type info = {
mobile: string,
dl:string,
aadhar: string,
name: string
}
type infoMandatory = {
mobile: string,
dl?:string,
aadhar?: string,
name?: string
}|{
mobile?: string,
dl:string,
aadhar?: string,
name?: string
}|{
mobile?: string,
dl?:string,
aadhar: string,
name?: string
}|{
mobile?: string,
dl?:string,
aadhar?: string,
name: string
}
type MarkReq<Obj, RequiredKey extends keyof Obj> = Required<Pick<Obj, RequiredKey>> & Partial<Omit<Obj, RequiredKey>>
type MarkReqWithOtherOriginal <Obj, RequiredKey extends keyof Obj> = Required<Pick<Obj, RequiredKey>> & Omit<Obj, RequiredKey>;
type A<K extends keyof info> = {
"mobile": MarkReq<info, "mobile">,
"dl": MarkReq<info, "dl">,
"aadhar": MarkReq<info, "aadhar">,
"name": MarkReq<info, "name">
}[K]
const b:A<"aadhar" | "dl"> = {
mobile: "sd",
aadhar: "sd"
}
type AtleastThis<Obj, AtleastOneOfTheseNeeded extends keyof Obj = keyof Obj>= {[key in keyof Obj]: MarkReq<Obj, key>}[AtleastOneOfTheseNeeded]
const a:AtleastThis<info, "aadhar"|"dl"|"mobile"> = {
"name":"hg",
"mobile":"h"
}
const person:AtleastThis<info, "aadhar" | "dl"> & MarkReq<Pick<info, "name">, "name"> = {
name: "sd",
aadhar: "sd"
}
type AtleastThisWithThatReq <Obj, AtleastOneNeeded extends keyof Obj, MandatoryKey extends keyof Omit<Obj, AtleastOneNeeded>> = AtleastThis<Obj, AtleastOneNeeded> & MarkReq<Pick<Obj, MandatoryKey>, MandatoryKey>
const obj:AtleastThisWithThatReq<info, "aadhar" | "dl" , "name"> = {
"name": "dsd",
"aadhar":"sd"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment