TypeScript Support
The Moitribe JavaScript SDK provides comprehensive TypeScript support with built-in type definitions, enabling type-safe development and better IDE assistance.
Installation
Install the SDK with TypeScript support:
npm install @veniso/moitribe-js
npm install --save-dev @types/node
yarn add @veniso/moitribe-js
yarn add --dev @types/node
TypeScript Configuration
Configure your tsconfig.json for optimal SDK usage:
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"lib": ["ES2020", "DOM"],
"declaration": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Basic Usage
Import and use the SDK with full TypeScript support:
import MoitribeSDK, {
Logger,
LogLevel,
StatusCodes,
type SignedInProfile,
type Player,
type CallbackFunction
} from '@veniso/moitribe-js';
// Type-safe SDK initialization
const gameId = 'my-game-id';
// Callback with proper typing
const loginCallback: CallbackFunction<{ success: boolean }> = (result) => {
console.log('Login result:', result.success);
};
// Initialize with typed parameters
MoitribeSDK(gameId, 'isAuthenticated', {}, (result: { authenticated: boolean }) => {
if (result.authenticated) {
console.log('Player is authenticated');
}
});
Type-Safe Method Calls
All SDK methods support proper TypeScript typing:
// Profile management with types
MoitribeSDK(gameId, 'getprofile', {}, (profile: SignedInProfile) => {
console.log('Player name:', profile.name);
console.log('Player level:', profile.level);
console.log('Friends count:', profile.friends.length);
});
// Leaderboard operations
MoitribeSDK(gameId, 'submitscore', {
leaderboardid: 'high-scores',
score: 1000,
scoretag: 'daily-challenge'
}, (result: { success: boolean; newRank?: number }) => {
console.log('Score submitted:', result.success);
if (result.newRank) {
console.log('New rank:', result.newRank);
}
});
// Real-time multiplayer
MoitribeSDK(gameId, 'createstandardroom', {
maxPlayers: 4,
variant: 1
}, (result: { success: boolean; roomId?: string }) => {
if (result.success && result.roomId) {
console.log('Room created:', result.roomId);
}
});
Advanced Type Usage
Custom Type Definitions
Create interfaces for your game-specific data:
interface GameScore {
playerId: string;
score: number;
timestamp: number;
metadata?: {
level: number;
moves: number;
};
}
interface CustomRoomData {
gameMode: 'classic' | 'timed' | 'endless';
difficulty: 'easy' | 'medium' | 'hard';
}
// Use with SDK callbacks
const submitGameScore = (score: GameScore) => {
MoitribeSDK(gameId, 'submitscore', {
leaderboardid: 'game-scores',
score: score.score,
scoretag: JSON.stringify(score.metadata)
}, (result) => {
console.log('Game score submitted:', result.success);
});
};
Generic Callback Types
Create reusable callback types for your application:
type SuccessCallback<T = any> = (result: { success: boolean; data?: T }) => void;
type ErrorCallback = (error: { code: number; message: string }) => void;
const handleSDKCall = <T>(
method: string,
params: any,
onSuccess: SuccessCallback<T>,
onError?: ErrorCallback
) => {
MoitribeSDK(gameId, method, params, (result) => {
if (result.success) {
onSuccess(result);
} else if (onError) {
onError({ code: result.code || -1, message: result.message || 'Unknown error' });
}
});
};
// Usage
handleSDKCall<{ profile: SignedInProfile }>(
'getprofile',
{},
(result) => {
if (result.data?.profile) {
console.log('Profile loaded:', result.data.profile.name);
}
},
(error) => {
console.error('Profile load failed:', error.message);
}
);
Enum Usage
Use the provided enums for type-safe constants:
import { LogLevel, StatusCodes, RoomStatus, ParticipantStatus } from '@veniso/moitribe-js';
// Configure logging with enum
Logger.setLogLevel(LogLevel.DEBUG);
// Handle status codes
const handleAPIResponse = (statusCode: number) => {
switch (statusCode) {
case StatusCodes.STATUS_OK:
console.log('Operation successful');
break;
case StatusCodes.STATUS_SIGNED_IN_PLAYER_REQUIRED:
console.log('Player authentication required');
break;
case StatusCodes.STATUS_LEADERBOARD_SUBMIT_SCORE_FAILED:
console.log('Score submission failed');
break;
default:
console.log('Unknown status code:', statusCode);
}
};
IDE Support
With proper TypeScript configuration, you'll get:
- Auto-completion for all SDK methods and parameters
- Type checking to catch errors at compile time
- Inline documentation on hover
- Refactoring support for safe code changes
- IntelliSense for better development experience
Next Steps
- Type Definitions - Complete reference of available types
- Error Handling - Handle errors with TypeScript
- Callback Patterns - Understanding callback types
tip
Enable strict mode in your TypeScript configuration for the best type safety and error detection.