#Does this produce a type with a property of the right name and type from another type?

9 messages · Page 1 of 1 (latest)

eager geode
#

ignoring the possible mess when T and T2 have the same property name but different types, is this how I would right a (relatively) type safe graft function?

export function addPropFromOtherType<T extends object | null, T2, K extends keyof T2>(item: T, key: K, value: T2[K]): (T & T2[K]) | null {
    if (!item) return null;
    (item as any)[key] = value;
    return item as T & T2[K];
}

Is there an easier way such that I could somehow specify just T2 at call sites so intellisense would detect my options for key?

#

nah, attempted usage shows it doesn't do that... not sure how to dynamically add a value from another type this way

eager sandal
#

i'm not sure why T2 needs to come into the picture at all:

orchid abyssBOT
#
export function addPropFromOtherType<T extends object, K extends PropertyKey, V>(item: T, key: K, value: V): T & Record<K, V> {
    const augmentableItem: Partial<Record<K, V>> = item
    augmentableItem[key] = value;
    return augmentableItem as T & Record<K, V>;
}
eager sandal
#

if you're returning the new item anyway, i might suggest this safer version that doesn't mutate its argument:

orchid abyssBOT
#
export function addPropFromOtherType<T extends object, K extends PropertyKey, V>(item: T, key: K, value: V): T & Record<K, V> {
    const augmentation = { [key]: value } as Record<K, V>
    return {
        ...item,
        ...augmentation
    }
}
eager sandal
eager geode
#

I'll give that a go in the morning when I'm back at work

eager geode
#

that appears to work, really nice.