0
0

More than 1 year has passed since last update.

The operand of a 'delete' operator must be optionalエラー

Posted at

The operand of a 'delete' operator must be optionalエラー

困ったこと

TypeScriptで開発中、バリデーションの結果をJSON形式で返すAPIを作成しようとした。

request
{ code:"1234567890" }
バリデーションOKのresponse
{ result:true }
バリデーションNGのresponse
{ result:false error:"codeの桁数が不正です" }

上記機能実装のために以下のようにコーディングしたところ
「The operand of a 'delete' operator must be optional」というようなエラーが発生した。

format.ts
interface resultFormat {
	result: boolean;
	error:string;
}
export { resultFormat } ;
api.ts
import { resultFormat } from "./format.ts";
const exampleAPI = (
	req: Express.Request,
	res: Express.Response
) => {
	if (req.data.code.length === 10) {
		const resData: resultFormat = {
			result:false,
			error:"codeの桁数が不正です"
		};
	res.json(resData);
	} else {
		const resData: resultFormat = {
			result: true,
			error:""
		};
		delete resData.error;
		res.json(resData);
	}
};

解決策

format.ts
interface resultFormat {
	result: boolean;
	error:string;
}
interface resultErrorFormat {
	result: boolean;
}
export { resultFormat,resultErrorFormat }  ;
api.ts
import { resultFormat,resultErrorFormat } from "./format.ts";
const exampleAPI = (
	req: Express.Request,
	res: Express.Response
) => {
	if (req.data.code.length === 10) {
		const resData: resultFormat = {
			result:false,
			error:"codeの桁数が不正です"
		};
	res.json(resData);
	} else {
		const resData: resultErrorFormat = {
			result: true,
		};
		res.json(resData);
	}
};

まとめ

TypeScriptでinterfaceにて定義した型から外れるようなオブジェクトのdeleteを行おうとすると
「The operand of a 'delete' operator must be optional」エラーが発生するようだ。
条件によって返すJSON(オブジェクト)の形式が異なる場合はそれぞれにintarface(型)を定義する必要がある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0