A
arktype4mo ago
Dimava

Generic with Narrow/Morph

I want to make something like
type UniqueArray<T, K extends keyof T>


export const UniqueArray = brandsScope.type.generic('T', 'K extends keyof T', ['T[]', ':', (v, ctx) => {
let vals = new Set(v.map(e => e[erm what]))
if (vals.length !== v.length) return ctx.mustBe(`array with uniue $K`)
return true
}])
type UniqueArray<T, K extends keyof T>


export const UniqueArray = brandsScope.type.generic('T', 'K extends keyof T', ['T[]', ':', (v, ctx) => {
let vals = new Set(v.map(e => e[erm what]))
if (vals.length !== v.length) return ctx.mustBe(`array with uniue $K`)
return true
}])
Please help me to make it work
2 Replies
Dimava
DimavaOP4mo ago
export const UniqueArray = function <const def, const key extends keyof Type<type.infer<def>>['infer'] & string>(
def: type.validate<def, brandsScope['t']>, key: key,
) {
return type([
[def as { key: 'string' }, '[]'], ':', (v, ctx) => {
const set = new Set(v.map(e => e[key as 'key']))
if (set.size !== v.length)
ctx.mustBe(`with unique values of ${JSON.stringify(key)}`)
return true
},
])
}
export const UniqueArray = function <const def, const key extends keyof Type<type.infer<def>>['infer'] & string>(
def: type.validate<def, brandsScope['t']>, key: key,
) {
return type([
[def as { key: 'string' }, '[]'], ':', (v, ctx) => {
const set = new Set(v.map(e => e[key as 'key']))
if (set.size !== v.length)
ctx.mustBe(`with unique values of ${JSON.stringify(key)}`)
return true
},
])
}
this does work but I want to see how generics work
ssalbdivad
ssalbdivad4mo ago
This isn't supported yet https://github.com/arktypeio/arktype/issues/1053 I don't really understand how K is relevant for a unique array anyways
Want results from more Discord servers?
Add your server