Created
July 12, 2021 08:26
-
-
Save shqld/c70878ae7775f6037459311094aeb58b to your computer and use it in GitHub Desktop.
Required / Optional prop definition by name
This file contains hidden or 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
type RequiredPropName<T extends string> = `${T}!` | |
type OptionalPropName<T extends string> = `${T}?` | |
type QualifiedPropName<T extends string> = RequiredPropName<T> | OptionalPropName<T> | |
type RequiredProp<T> = { | |
value: T, | |
required: true | |
} | |
type OptionalProp<T> = { | |
value: T, | |
required: false | |
} | |
type QualifiedProp<T> = RequiredProp<T> | OptionalProp<T> | |
const b = < | |
PropNameWithQualifier, | |
PropName extends string, | |
ReturnValue extends PropNameWithQualifier extends RequiredPropName<PropName> ? RequiredProp<PropName> : OptionalProp<PropName> | |
>(arg: PropNameWithQualifier & QualifiedPropName<PropName>): ReturnValue => { | |
const qualifier = arg[-1] | |
return { | |
value: arg.slice(0, -1), | |
required: qualifier === '!' | |
} as ReturnValue | |
} | |
const props = { | |
id: b('id!'), | |
name: b('name!'), | |
sex: b('sex?'), | |
age: b('age?'), | |
} | |
props |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment