1

I remember there is a way to create, inside an interface, a field without specifying its name, something like this:

export interface myInterface{
 [propName:string]:string;
}

If I remember well, that sinthax means I can create a field with whatever name I want, something like this:

ob:myInterface = {customName: "value"}

What I'm trying to do now is to add a new field to that interface, with a specific name, something like this:

export interface myInterface{
 [propName:string]:string;
 secondProperties: boolean;
}

When I try the code above I get this error:

Property 'secondProperties' of type 'boolean' is not assignable to string index type 'string'

What is my error?

1
  • Could you please share your problem with stackblitz.com ? Commented May 31, 2021 at 12:15

3 Answers 3

2

You need to define all possible types for [propName: string] So you need to do it in this way

export interface myInterface{
  secondProperties: boolean
  [propName:string]: string | boolean;
}
Sign up to request clarification or add additional context in comments.

Comments

2

I never found a good solution but the problem arises from this.

You are trying to force a property to be of type boolean & string, which equals to never.

type myInterface = {
    [propName:string]: string;
} & {
    secondProperties: boolean;
};

const obj: myInterface = {
    secondProperties: true,
};

playground


Thanks to @LaytonGB for hinting, that | can be used to make almost the type we wanted.

type myInterface = {
    [propName:string]: string;
} | {
    secondProperties: boolean;
};

const obj: myInterface = {
    secondProperties: 'string' || true,
    otherProps: 'string only', // booleans will result in error.
};

3 Comments

With the example you have used here, changing the & to a vertical line | seems to work like OP required.
Solutions provided by LaytonGB e CyberEternal seem to work
Though the other methods work, they do not perform the same ideal type-checking. If you create an object, { propName1: "foo", secondProperties: true, propName3: false } then this method (when using an | instead of & on line 3) will show propName3 to be an error. The other methods will not.
1

Because you have defined any string-named-property of your objects to have a value of string, you can only give secondProperties a string value, because secondProperties itself is a string.

Alternatively consider this:

interface myInterface {
  [propName: string]: string | boolean;
  ["secondProperties"]: boolean;
}

Because secondProperties is a string, and its value returns a boolean, it is not throwing errors.

1 Comment

Thank you, your explanation is really clear :)

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.