From a811b0948fbf635bfbc5c569a864b09cd7936ca5 Mon Sep 17 00:00:00 2001 From: Iku-turso Date: Thu, 6 Oct 2022 12:53:03 +0300 Subject: [PATCH] Introduce way to type narrow a string property Co-authored-by: Janne Savolainen Signed-off-by: Iku-turso --- src/common/utils/type-narrowing.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/common/utils/type-narrowing.ts b/src/common/utils/type-narrowing.ts index d2d33929a2..936fb48816 100644 --- a/src/common/utils/type-narrowing.ts +++ b/src/common/utils/type-narrowing.ts @@ -35,6 +35,15 @@ export function hasTypedProperty(val return hasOwnProperty(val, key) && isValid(val[key]); } +/** + * Narrows `val` to include the property `key` with type string + * @param val the value that we are trying to type narrow + * @param key The key to test if it is present on the object (must be a literal for tsc to do any meaningful typing) + */ +export function hasStringProperty(val: S, key: K): val is (S & { [key in K]: string }) { + return hasOwnProperty(val, key) && isString(val[key]); +} + /** * Narrows `val` to include the property `key` with type `V | undefined` or doesn't contain it * @param val the value that we are trying to type narrow