Open lo1tuma opened 3 years ago
Are you aware of any TypeScript issues about it? Would you be able to link some?
From a quick search, https://github.com/microsoft/TypeScript/pull/38839 looks relevant.
I haven’t really checked the TypeScript issues before. It looks like that microsoft/TypeScript#38839 could fix this problem. I’ve also found this issue https://github.com/microsoft/TypeScript/issues/34974.
It seems likely to be extended to a function that verify the schema of an object.
Some ideas are as follows.
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;
// }
}
There is a similar implementation in ow
. https://github.com/sindresorhus/ow/issues/92
I would like to propose a new function
is.propertyOf(object: unknown: key: string, predicate: Predicate): boolean
that accepts 3 values and checks:key
andExample Usage:
Why
Given the following example
Unfortunately typescript is not smart enough to understand that within the
if
blockfoo
is always defined.Let’s say
is.propertyOf
is implemented similar to this:then the code from above could look like this: