From f367afc460977b1280bb679031e07e9247e232b5 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Tue, 11 Feb 2020 16:44:24 +0800 Subject: [PATCH] Add assertAsMap method --- main.tea | 6 ++++++ ts/src/client.ts | 7 +++++++ ts/test/client.spec.ts | 14 ++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/main.tea b/main.tea index f3fad8ee..94c32072 100644 --- a/main.tea +++ b/main.tea @@ -131,3 +131,9 @@ static function isUnset(value: any): boolean; * @return the new stringified map */ static function stringifyMapValue(m: map[string]any): map[string]string; + +/** + * Assert a value, if it is a map, return it, otherwise throws + * @return the map value + */ +static function assertAsMap(value: any): map[string]any; diff --git a/ts/src/client.ts b/ts/src/client.ts index 689315bd..4004d195 100644 --- a/ts/src/client.ts +++ b/ts/src/client.ts @@ -173,4 +173,11 @@ export default class Client { } return result; } + + static assertAsMap(value: any): {[key: string]: any} { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value as {[key: string]: any}; + } + throw new Error(`The value is not a object`); + } } diff --git a/ts/test/client.spec.ts b/ts/test/client.spec.ts index d2e5b6ca..1d5eb3fe 100644 --- a/ts/test/client.spec.ts +++ b/ts/test/client.spec.ts @@ -116,4 +116,18 @@ describe('Tea Util', function() { assert.deepStrictEqual(Client.stringifyMapValue({'bool': true}), {'bool': 'true'}); assert.deepStrictEqual(Client.stringifyMapValue(null), null); }); + + it('assertAsMap', function () { + assert.deepStrictEqual(Client.assertAsMap({}), {}); + assert.throws(() => { + Client.assertAsMap([]); + }, /The value is not a object/); + assert.throws(() => { + Client.assertAsMap(true); + }, /The value is not a object/); + assert.throws(() => { + Client.assertAsMap(123); + }, /The value is not a object/); + }); + });