gpt4 book ai didi

javascript - 分配时不强制执行 Typescript 字段类型

转载 作者:行者123 更新时间:2023-12-02 23:30:56 25 4
gpt4 key购买 nike

我有一个设置_device值的构造函数,该字段的类型为number,构造函数参数的类型为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 捕获此错误并在编译时或运行时抛出某种错误。

最佳答案

TypeScript 不执行运行时检查。事实上你已经告诉了它

playerData: { 
name: string,
device: number
}

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

关于javascript - 分配时不强制执行 Typescript 字段类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com