Skip to content

Advanced

Narcis B edited this page Nov 27, 2021 · 6 revisions

Events type-safe

The new types offer some methods that will facilitate your development by auto-complete and also type-safe.

// @types/index.d.ts
declare global {
    interface IServerEvents {
        playerLeaveHouse: (player: PlayerMp, houseId: number) => void;
    }
}

export {};
See in action See in action

Cancelable events type-safe.

For cancelable events, we need to declare a handler as a function (does not work with arrow-function)

WRONG!

mp.events.add('playerReady', (player) => {
    this.cancel = true; 
});

The above example will throw some errors.

The containing arrow function captures the global value of 'this'.ts(7041)

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017)

GOOD! 👍

mp.events.add('playerReady', function (player) {
    this.cancel = true; 
});
See in action See in action

Class prototype type-safe

// @types/index.d.ts
declare global {
    interface PlayerMp {
        myMethod: () => void;
    }
}

export {};
See in action See in action
Clone this wiki locally