ofir_aghai
ofir_aghai

Reputation: 3281

String variable value as a property in a type

i try to create a type which has a variable value as a property

For example:

const myProp: string = 'my prop';
type Foo ={ 
    [myProp]: string
};

i expected that i can do:

const test: Foo = {
   [myProp] = myProp
}

But get error of:

[ts] A computed property name in a type literal must directly refer to a built-in symbol.

Upvotes: 1

Views: 1322

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249476

If you want to declare a type that has the same property name as a string constant you could use the following syntax (lookup type syntax)

const myProp = 'my prop';
type Foo = {
    [P in typeof myProp]: string
};
const test: Foo = {
    [myProp]: myProp
}

If you want to have several of these keys you can use a union type :

const myProp = 'my prop';
const otherProp = "otherProp"
type Foo = {
    [P in (typeof myProp | typeof otherProp)]: string
};
const test: Foo = {
    [myProp]: myProp,
    [otherProp]: otherProp
}

The typescript default libraries, actually provides a type that is equivalent to the above lookup type declaration, named Record. Using this you could write your type as:

type Foo2 = Record<typeof myProp, string>;

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37918

You will able to do this once next version of Typescript released.

This feature already available in typescript@next. If you want to, you can install it with:
npm install typescript@next --save-dev

Meanwhile you can use method provided by @Titian Cernicova-Dragomir

Upvotes: 1

Related Questions