Is there a way to distinguish if interface property is required, or not in runtime? Suppose we have:
export interface IPagination {
mode: PaginationMode;
pageSizes: number[];
defaultPageSize?: number;
}
Now in runtime I need to read a configuration from some JSON file, save it to some property of type IPagination, and want to use interface metadata to check validity of configuration (in my case if I have two configs, one with defaultPageSize and another without, they'd both be valid). Is this possible to do, using interface information?
I would use two different types in this case, and a type guard to differentiate them.
export type Pagination = {
mode: PaginationMode;
pageSize: number[];
};
export type PaginationWithDefaultPageSize = Pagination & {
defaultPageSize: number;
};
// Example function that shows how to use a typeguard:
function checkPagination(config: Pagination | PaginationWithDefaultPageSize) {
hasDefaultPageSize(config)
? console.log(`The default page size is ${config.defaultPageSize}`);
: console.log('This is a normal Pagination config, without a default page size.');
}
// This is the typeguard:
function hasDefaultPageSize(config: Pagination | PaginationWithDefaultPageSize): config is PaginationWithDefaultPageSize {
return 'defaultPageSize' in config;
}
With the typeguard, TypeScript will know that the type of config
is either Pagination
or PaginationWithDefaultPageSize
, and you can access the different properties of those two types.
Update:
If you just want to validate that your object is OK and contains all required keys, it is not possible with TypeScript. TypeScript is a transpiler, not a validator.
I would still write a typeguard like this:
function isValidPaginationConfig(config: any | Pagination): config is Pagination {
return 'mode' in config
&& 'pageSizes' in config
&& Array.isArray(config.pageSizes);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.