ts-indexify
v1.0.0
Published
Add index signature to interface
Downloads
1
Maintainers
Readme
ts-indexify
Add index signature to interface
Why?
Plain interface is not assignable to Record type because Index signature is missing in type (only on interfaces, not on type alias)
How?
Convert interface to a type with an index signature using the keys of the interface.
/**
Add index signature to interface
*/
export declare type Indexify<O extends object> = {
[P in keyof O]: O[P];
};
/**
Constructs a index signature to interface
*/
export declare const indexify: <O extends object>(object: O) => Indexify<O>;
Here is a comparison with default behavior.
type Dict = Record<string, unknown>;
/**
Default behavior
*/
expectAssignable<Dict>(someObject);
expectAssignable<Dict>(someObject as SomeType);
expectNotAssignable<Dict>(someObject as SomeInterface); // Index signature is missing in interface
expectNotAssignable<Dict>(someInstance); // Index signature is missing in class
/**
Indexify
*/
expectAssignable<Dict>(indexify(someObject));
expectAssignable<Dict>(indexify(someObject as SomeType));
expectAssignable<Dict>(indexify(someObject as SomeInterface));
expectAssignable<Dict>(indexify(someInstance));
It does not affect runtime behavior.
Install
npm install ts-indexify
Usage
import {indexify, Indexify} from 'ts-indexify';
interface SomeInterface {
foo: number;
bar?: string;
baz: number | undefined;
}
const someObject: SomeInterface = {foo: 123, bar: 'hello', baz: 456};
function fn(object: Record<string, unknown>): void {}
fn(someObject); // error
fn(indexify(someObject)); // work
fn(someObject as Indexify<SomeInterface>); // work