1

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.

2 Answers 2

2

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>;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answare :)
1

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

1 Comment

Thanks for your answare. Maybe this will be my solution in the next time, but currently the answer of @Titan saved my day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.