Skip to content

Commit

Permalink
feat: strict string typings (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
LiamMartens authored Feb 26, 2022
1 parent deda478 commit ced678d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/schema/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,13 +363,13 @@ interface SpanField extends BaseField {
validation?: Validator
}

interface StringField extends BaseField {
interface StringField<S extends string = string> extends BaseField {
type: 'string'
options?: {
/**
* A list of predefined values that the user can choose from. The array can either include string values ['sci-fi', 'western'] or objects [{title: 'Sci-Fi', value: 'sci-fi'}, ...]
*/
list?: Array<string | { title: string; value: string }>
list?: Array<S | { title: string; value: S }>
/**
* Controls how the items defined in the list option are presented. If set to 'radio' the list will render radio buttons. If set to 'dropdown' you'll get a dropdown menu instead. Default is dropdown.
*/
Expand Down Expand Up @@ -458,10 +458,15 @@ export type FieldType<
: T extends
| PureType<'date'>
| PureType<'datetime'>
| PureType<'string'>
| PureType<'text'>
| PureType<'url'>
? string
: T extends PureType<'string'>
? T extends {
options: { list: Array<infer S | { title: string; value: infer S }> }
}
? S
: string
: T extends PureType<'file'>
? File
: T extends PureType<'geopoint'>
Expand Down
18 changes: 18 additions & 0 deletions test/types/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,24 @@ describe('field types', () => {
.use()[1]
expectTypeOf(string).toEqualTypeOf<string>()

/**
* enum like string example
*/
enum AllowedStringValues {
FOO = 'foo',
BAR = 'bar',
}
const enumString = defineDocument('enumStringExample', {
test: {
type: 'string',
options: { list: [AllowedStringValues.FOO, AllowedStringValues.BAR] },
},
})
.builder.pick('test')
.first()
.use()[1]
expectTypeOf(enumString).toEqualTypeOf<AllowedStringValues>()

/**
* 'text'
*/
Expand Down

0 comments on commit ced678d

Please sign in to comment.