'Typescript: Type narrowing - a parameter type that checks if Type name contains another Type name [closed]
Is there a way to narrow the type that if type name contains particular name?
Example 1: The key name contains other key name.
interface IFooBar {
foo: string;
bar: string;
baz: string;
fooBar: string;
}
const obj: IFooBar = {...};
keyof IFooBar - isn't the option - all keys allowed;
The motivation is - narrow the key type (foo, bar, fooBar only) and avoid hardcoding allowed keys like in this example - Typescript: check if value is contained in type
*// error for "baz";*
const someFunc<T extends `${fooBar}`.includes(`${foo}`) | `${fooBar}`.includes(`${bar}`)> = (key: T) => Object.keys(obj)... ;
Example 2: Type name contains another type name
type Foo= 'Foo';
type FooBar = 'FooBar';
type Baz = 'Baz';
*// error for Baz;*
const someFunc2<T extends `${FooBar}`.includes(`${Foo}`) => {...};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
