0

How would I access a field/property of an interface with a string that represents the field in Typescript.

For instance, if we have a interface such as,

export interface foo {
    field1: boolean;
    field2: boolean;

where foo.field1 = true

I want to create a command that returns the value of a field such as,

public findValue(f: string): boolean {
    return foo.f;
}

However, ^ of course this does not work since f is a string. But is there a way to do this in Typescript?

vicki
  • 225
  • 2
  • 10
  • 1
    foo[f] . as simple as that :) – Julien Jun 08 '21 at 19:50
  • 1
    Obviously, you're going to need an object that implements `foo`, because `foo` doesn't exist at runtime. – Heretic Monkey Jun 08 '21 at 19:52
  • 1
    You have not defined a value named `foo`; the `interface` exists only in the type system (and as a non-primitive type, the convention would be to call it `Foo` using UpperCamelCase). If you want `foo[f]` to work, you need a `foo`. Please consider modifying this code to constitute a [mcve] that demonstrates your issue when dropped into a standalone IDE like [The TypeScript Playground](https://tsplay.dev/WvpeRN). – jcalz Jun 08 '21 at 19:53
  • The answer code will look [like this](https://tsplay.dev/WyvYdw), but the question should ideally be modified first. – jcalz Jun 08 '21 at 19:56
  • Yes, an object is needed, and also add an indexer definition on your interface. This [Codesandbox](https://codesandbox.io/s/silly-lichterman-ndpek) should give you an idea. – AWolf Jun 08 '21 at 20:00

0 Answers0