0

In TypeScript, it is possible for a type declaration to allow for dynamic object properties?

class Animal {
    name: string;
    [everything else]: any;
}

let animal = <Animal>{ name: "Kitty", type: "cat" };

animal.name; // Would be treated as string

animal.type; // Would allow compilation and be treated as any

I would like these extra properties to be allowed dynamically, without having to add them to the type declaration. Using TypeScript 1.8.2.

1 Answer 1

1

Yes, like this:

class Animal {
    name: string;
    type?: any;
}

But I would suggest using an Enum for type like this:

enum AnimalType {Cat, Dog, ...};

class Animal {
    name: string;
    type?: AnimalType;
}
Sign up to request clarification or add additional context in comments.

4 Comments

What about colour for example? I want the extra properties to be allowed without having to add them to the type.
This should not give an error at all: See typescriptlang.org/…
I think you have to use it similar to a map but I am not sure if that is a good idea: typescriptlang.org/…

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.