Introduce way to type narrow a string property

Co-authored-by: Janne Savolainen <janne.savolainen@live.fi>

Signed-off-by: Iku-turso <mikko.aspiala@gmail.com>
This commit is contained in:
Iku-tursoandJanne Savolainen authored and Janne Savolainen committed 2022-10-20 08:37:14 +03:00
1 parent cf9bf23ac5
commit a811b0948f
1 file changed
+9
+9
View File
@@ -35,6 +35,15 @@ export function hasTypedProperty<S extends object, K extends PropertyKey, V>(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<S extends object, K extends PropertyKey>(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