A
arktype3mo ago
Dimava

Extenting Type interface

I want to make a custom function type({}).migrate() and add it to BaseType prototype How do I do it properly?
2 Replies
ssalbdivad
ssalbdivad3mo ago
Sadly would be very convoluted. You'd have to do something hacky like modifying the BaseRoot prototype directly to add it or you could create a constructor that just delegates to arktype then assigns the extra method to it
Dimava
DimavaOP3mo ago
import type { Type } from 'arktype'
import type { Out } from 'arktype/out/keywords/inference'
import { BaseRoot } from '@ark/schema'
import { type } from 'arktype'

declare module 'arktype/out/methods/base' {
interface BaseType {
migrate(...migrators: type.Any[]): Type<(In: unknown) => Out<this['infer']>>
}
}

Object.assign(BaseRoot.prototype, {
migrate(this: type.Any, ...migrations: type.Any[]) {
return type('unknown.any')
.pipe((v, _ctx) => {
const result = this(v)
if (!(result instanceof type.errors))
return result
for (const migration of migrations) {
const migResult = migration(v)
if (!(migResult instanceof type.errors)) {
v = migResult
}
}
return this(v)
})
},
})
import type { Type } from 'arktype'
import type { Out } from 'arktype/out/keywords/inference'
import { BaseRoot } from '@ark/schema'
import { type } from 'arktype'

declare module 'arktype/out/methods/base' {
interface BaseType {
migrate(...migrators: type.Any[]): Type<(In: unknown) => Out<this['infer']>>
}
}

Object.assign(BaseRoot.prototype, {
migrate(this: type.Any, ...migrations: type.Any[]) {
return type('unknown.any')
.pipe((v, _ctx) => {
const result = this(v)
if (!(result instanceof type.errors))
return result
for (const migration of migrations) {
const migResult = migration(v)
if (!(migResult instanceof type.errors)) {
v = migResult
}
}
return this(v)
})
},
})
I guess this works well enough then
Want results from more Discord servers?
Add your server