1

I have a function template like this:

function (..., args: any) {...}

And I have a class called CreateLobbyParameter :

export class CreateLobbyParameter {
    userId: number;
    gameMode: GameMode;
}

If given any typed args parameter is not similar to CreateLobbyParameter (e.g. {userId: 0, gameMode: 0}, but not {userId:0}); I wanna handle that situation.

I've tried typeof(arg as CreateLobbyParameter), but it returns the string "object" for the parameter {userId: 0, gameMode: 0}, and not CreateLobbyParameter.

Also, arg instanceof CreateLobbyParameter returns false.

6
  • Not very clear what are you trying to do, are you trying to type a function that takes any as an argument? Commented Dec 27, 2017 at 16:03
  • Is GameMode an enumeration or another class? Commented Dec 27, 2017 at 16:04
  • You should probably define an interface for args instead of typing it as any. Commented Dec 27, 2017 at 16:05
  • GameMode is an enum. Commented Dec 27, 2017 at 16:10
  • Johnny, but it's properties are flexible, they change depending to its place. Commented Dec 27, 2017 at 16:12

2 Answers 2

2

Treat it like JavaScript.

var userId = arg.userId;
var gameMode = arg.gameMode;
if (userId && gameMode) {
   var myCreateLobbyParameter = new CreateLobbyParameter {
      userId = userId,
      gameMode = gameMode
   }
}

Then you have a real CreateLobbyParameter object to work with, or you can do whatever with a non-conforming argument.

Sign up to request clarification or add additional context in comments.

3 Comments

I have noImplicitAny option turned on, but let me try to adapt the code.
This worked out, when I gave any types to them, thanks for helping.
Happy to help :)
0

I actually found another way:

export function isSimilar(object: any, target: any): boolean {
    if (typeof(object) !== object && (typeof(object) !== typeof(target))) {
        return true;
    }
    const keys: string[] = Object.keys(object);
    const targetKeys: string[] = Object.keys(target);
    return !keys.every(x => targetKeys.indexOf(x) >= 0);
}

Usage:

hasNull(args, new CreateLobbyParameter());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.