Skip to content
On this page

2021-12-14

Title
2021-12-14
Category
2021
Tags
Aliases
2021-12-14
Related
Created
2 years ago
Updated
last year
  • Proposal: validate type of object properties · Issue #141 · sindresorhus/is (github.com) #issues

    ts
    import is from '@sindresorhus/is';
    import {objectEntries, objectHasOwn} from 'ts-extras';
    
    const isInterface = <ObjectType extends Record<string, unknown>>(
    	value: unknown,
    	interface_: {
    		[Key in keyof ObjectType]: (value: unknown) => value is ObjectType[Key];
    	},
    ): value is ObjectType => {
    	return objectEntries(interface_).every(
    		([key, predicate]) => objectHasOwn(value, key) && predicate(value[key]),
    	);
    };
    
    declare const someObject: unknown;
    
    if (
    	isInterface(someObject, {
    		foo: is.string,
    		bar: is.number,
    		baz: is.boolean,
    	})
    ) {
    	someObject;
    	// {
    	//     foo: string;
    	//     bar: number;
    	//     baz: boolean;
    	// }
    }
    
    import is from '@sindresorhus/is';
    import {objectEntries, objectHasOwn} from 'ts-extras';
    
    const isInterface = <ObjectType extends Record<string, unknown>>(
    	value: unknown,
    	interface_: {
    		[Key in keyof ObjectType]: (value: unknown) => value is ObjectType[Key];
    	},
    ): value is ObjectType => {
    	return objectEntries(interface_).every(
    		([key, predicate]) => objectHasOwn(value, key) && predicate(value[key]),
    	);
    };
    
    declare const someObject: unknown;
    
    if (
    	isInterface(someObject, {
    		foo: is.string,
    		bar: is.number,
    		baz: is.boolean,
    	})
    ) {
    	someObject;
    	// {
    	//     foo: string;
    	//     bar: number;
    	//     baz: boolean;
    	// }
    }
    

Vue

Released under the MIT License.