A
arktype2mo ago
Apteryx

How can I clone/make a new type without caching?

I want to assign a sort of metadata and additional methods directly to the type value, however, due to types being cached, those assignments will exist on every instance of that type signature. Is there anyway to disable caching for a single type, or clone an existing type so it has a new reference? Example of the sort of thing I want to do:
const User = type({ id: 'string' });
User.displayName = 'User';

const Post = type({ id: 'string' });
Post.displayName = 'Post';

console.log(User === Post); // true
console.log(User.displayName === 'Post'); // true
const User = type({ id: 'string' });
User.displayName = 'User';

const Post = type({ id: 'string' });
Post.displayName = 'Post';

console.log(User === Post); // true
console.log(User.displayName === 'Post'); // true
3 Replies
ssalbdivad
ssalbdivad2mo ago
the most straightforward thing would be to just add some metadata using arktype's builtin concept- has some other benefits like type safety as well:
declare global {
interface ArkEnv {
meta(): {
displayName: string
}
}
}

const User = type({ id: "string" }).configure({ displayName: "User" })

console.log(User.meta.displayName)
declare global {
interface ArkEnv {
meta(): {
displayName: string
}
}
}

const User = type({ id: "string" }).configure({ displayName: "User" })

console.log(User.meta.displayName)
Apteryx
ApteryxOP2mo ago
Even better, simply using .configure results in a new reference, cool
const User = type({ id: 'string' }).configure({ key: Math.random() });
User.displayName = 'User'

const Post = type({ id: 'string' }).configure({ key: Math.random() })
Post.displayName = 'Post'

console.log(User === Post); // false
console.log(User.displayName === 'Post'); // false
const User = type({ id: 'string' }).configure({ key: Math.random() });
User.displayName = 'User'

const Post = type({ id: 'string' }).configure({ key: Math.random() })
Post.displayName = 'Post'

console.log(User === Post); // false
console.log(User.displayName === 'Post'); // false
ssalbdivad
ssalbdivad2mo ago
Yeah that was kind of what I meant that as long as the metadata is different it will generate different references. I thought maybe you'd want to have safety around the metadata that was being added, but if you need it at the top-level this is fine

Did you find this page helpful?