Skip to content

Instantly share code, notes, and snippets.

@shqld
Created July 12, 2021 08:26
Show Gist options
  • Save shqld/c70878ae7775f6037459311094aeb58b to your computer and use it in GitHub Desktop.
Save shqld/c70878ae7775f6037459311094aeb58b to your computer and use it in GitHub Desktop.
Required / Optional prop definition by name
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