Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell TypeScript: to get `keyof importedObject`?

Tags:

typescript

My TypeScript v2.2.1, I have list of objects in my-module:

export const OneObj = { prop1: 'value1' }
export const TwoObj = { prop2: 'value2' }

I want to create new type in another module:

import * as importedObject from './my-module';

console.log(importedObject)
// { OneObj: { prop1: 'value1' }, TwoObj: { prop2: 'value2' } }}

type NewType = keyof importedObject;
// Error: Cannot find name 'importedObject'

Why TypeScript throw error?

Cannot find name 'importedObject'

And at the same time, I can do this:

type NewType = keyof { OneObj: { prop1: 'value1' }, TwoObj: { prop2: 'value2' } };

// NewType === ("OneObj" | "TwoObj")
like image 780
ktretyak Avatar asked Feb 27 '17 20:02

ktretyak


1 Answers

This seems a roundabout way, but I can do this:

import * as importedObject from './my-module';

type NewType = keyof typeof importedObject; // OK: "OneObj" | "TwoObj"
like image 93
ktretyak Avatar answered Dec 20 '22 23:12

ktretyak