分配时不强制使用Typescript字段类型

时间:2019-06-08 20:06:11

标签: javascript typescript

我有一个构造函数,该构造函数设置 _device 的值,该字段的类型为 number ,构造函数参数的类型为 number 好。

但是,当将 string 传递给构造函数时,它将把该字符串分配给字段(类型为number)。

除了严格检查传入参数的类型以确保其为数字外,我不确定还能尝试什么,我宁愿由Typescript来处理。

我在想我的问题是socketio参数如何传入。 可以声明这样的类型吗?

{
joinRoom: { 
          roomId: string, 
          intent: number
        }, 
        playerData: { 
          name: string,
          device: number
        }
}

播放器类

export class Player {
  private _name: string;
  private _socketId: string;
  private _isReady: boolean;
  private team: string;
  private _device: number;

 /**
  * Creates an instance of Player.
  * @param {string} name
  * @param {string} socketId
  * @param {number} device
  * @memberof Player
  */
  constructor(name: string, socketId: string, device: number) {
    this._name = name;
    this._isReady = false;
    this._socketId = socketId;
    this._device = device;
  }
...

RoomLogic类

/**
   * @private
   * @param {*} socket
   * @memberof RoomLogic
   */
  private joinRoom(socket: any) {
    socket.on(CONSTANTS.JOIN_ROOM, 
      (
        joinRoom: { 
          roomId: string, 
          intent: number
        }, 
        playerData: { 
          name: string,
          device: number
        }
      ) => {

      const noRooms = this.utils.isObjectEmpty(this._rooms);
      const roomAlreadyExists = !this.utils.isUndefined(this._rooms[joinRoom.roomId]);
      const isValid = this.isPlayerDataValid(playerData);

      if (isValid.isSuccessful === false) {
        return socket.emit(CONSTANTS.JOIN_ROOM, isValid);
      }

      if (this.utils.isSame(joinRoom.intent, JoinRoomIntents.CreateNewRoom)) {

        // should never be hit, but keep in case
        if (roomAlreadyExists) {
          return socket.emit(CONSTANTS.JOIN_ROOM, {
            isSuccessful: false,
            value: `room with id: ${joinRoom.roomId} already exists`
          });
        }

        let player = new Player(playerData.name, socket.id, playerData.device);
...

我希望发生的事情是Typescript在编译或运行时捕获到此错误并引发某种错误。

1 个答案:

答案 0 :(得分:1)

TypeScript不执行运行时检查。你已经说过的事实

playerData: { 
  name: string,
  device: number
}

允许TypeScript在编译时检查类型playerData.device与构造函数的device参数的预期类型是否匹配,这样做是正确的。如果您不相信传入的数据与您给定的类型声明相匹配,则还需要执行运行时检查。