1

Can you please tell me how to create a type containing types from the specified interface? Example:

interface SomeInterface { x:string y:number } 

expect to get something like

type SomeInterfaceTypes = string | number 

Necessary for the method that sets the fields of an object

let obj = {x: 'tst', y: 0} setObject( field: keyof SomeInterface: value: ??? ) { this.obj[field] = value } 

1 Answer 1

4

The answer to the question you actually asked is to use SomeInterface[keyof SomeInterface] (but keep reading):

interface SomeInterface { x:string y:number } type SomeInterfaceTypes = SomeInterface[keyof SomeInterface]; // ^? - SomeInterfaceTypes = string | number const a: SomeInterfaceTypes = "x"; // Works const b: SomeInterfaceTypes = 42; // Also works 

Playground link

But, I wouldn't use that type for your function, it would mean inst.setObject("x", 42) would work, even though x has the type string, not number.

Instead, use a generic function/method:

setObject<Key extends keyof SomeInterface>(field: Key, value: SomeInterface[Key]) { this.obj[field] = value; } 

That way, TypeScript can require that the key and value match up. The key's type is inferred from whatever you pass for the first argument, and then the value's type is inferred from the key's type. So this works:

inst.setObject("x", "ok"); 

...but this fails, because the value has the wrong type:

inst.setObject("x", 42); // ^^−−− Argument of type 'number' is not assignable to parameter of type 'string'.(2345) 

Playground link

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.