2

I am using latest TypeScript and Angular and i have an object:

const obj: ObjInterface = {
 prop1: 1,
 prop2: 2,
 prop3: '3'
}

Also i have interface based on that object:

interface ObjInterface {
  prop1: number;
  prop2: number;
  prop3: string;
}

Is it possible to create interface of the array that consist only from properties of the obj?

const array: SomeInterface = ['prop1', 'prop2', 'prop3']; // OK
const array: SomeInterface = ['prop1', 'prop2', 'prop4']; // error
1
  • 2
    Interfaces don't exist at runtime Commented May 7, 2018 at 9:38

1 Answer 1

1

You can create an array of keys of a type using the keyof operator

interface ObjInterface {
    prop1: number;
    prop2: number;
    prop3: string;
}
const array: Array<keyof ObjInterface> = ['prop1', 'prop2', 'prop3']; // OK
const array2: Array<keyof ObjInterface> = ['prop1', 'prop2', 'prop4']; // error

Note This will be a compile time error, at runtime you can have different strings in the array if you venture outside the type system or if you use type assertions.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.