How to extend Angular Signal and add array slice method?

Discussão em 'Angular' iniciado por Zachary Scott, Abril 14, 2025.

  1. Need a little help extending an Angular version 19 signal to include an Array slice method while still emitting signal changes. This is the first time I have worked with the Typescript type keyword (or signals for that matter.)

    My confusion is how to convey x as an array properly in the signalUpdateFn( node, (x) => {}) function below.
    The error is TS2345, Argument of type (x:A) => A[number][] is not assignable to (value:A) => A.

    --

    I'd use my custom signal type in a service or component, something like below, but never got to this point because of next section.

    // #products = signal< Product[] >( [] ); // traditional
    #myproducts:ExtendedSignal< Product[] > = signal< Product[] >( [] ); // attempt


    --

    Here's my attempt at extending a signal to include a custom method:

    import { CreateSignalOptions, signal, Signal, WritableSignal } from "@angular/core";
    import { SIGNAL, SignalGetter, signalUpdateFn } from "@angular/core/primitives/signals";

    // The & combines (intersects) the "types" of Signal, WritableSignal, and
    // { what we specify } together
    // <A> is a generic type parameter. I used A to represent an Array
    // extends [] I believe means A is constrained to be that object type of Array
    // or at least be an object that is not null, undefined, etc.

    export type ExtendedSignal<A extends []> = Signal<A> & WritableSignal<A> &
    {
    // Mimic Array function splice
    // splice(start, deleteCount, item1, item2, ...)

    splice(value: A, start:number, deleteCount:number, ...items:any): void;
    };

    export function extendedSignal<A extends []>(
    initialValue: A, options?: CreateSignalOptions<A>): ExtendedSignal<A> {

    const thissignal = signal<A>(initialValue) as SignalGetter<A> & WritableSignal<A>;
    const node = thissignal[SIGNAL];

    return Object.assign(thissignal, {
    splice: (value: A, start: number, deleteCount: number, ...items: any) =>
    signalUpdateFn(node, (x) => { // Error is here
    const arraycopy = [...value];
    arraycopy.splice(start, deleteCount, ...items);
    return arraycopy;
    })
    });
    }


    It underlines the (x) => { part with (x:A) => A[number][] cannot be assigned to (value:A) => A.

    I am sure I am confusing a few things, but this is how we learn. :)

    Continue reading...

Compartilhe esta Página