Is it possible to get the inferred type from an object when a type already is defined? Example:
type Foo = { [key: string]: string };
const foo: Foo = {
lorem: 'ipsum',
hello: 'world',
} as const;
type T = typeof foo;
/* Actual type:
type T = {
[key: string]: string;
};
*/
/* Wanted type:
type T = {
readonly lorem: 'ipsum';
readonly hello: 'world';
};
*/
CodePudding user response:
You can use the new TypeScript 4.9 feature satisfies
:
type Foo = { [key: string]: string };
const foo = {
lorem: 'ipsum',
hello: 'world',
} as const satisfies Foo;
type T = typeof foo;
/*
type T = {
readonly lorem: 'ipsum';
readonly hello: 'world';
};
*/