0

I will often make a string literal like this

type stringNumbers = 'One' | 'Two' | 'Three';

And use it in a class constructor

class myClass {
    display: stringNumbers;
    constructor(display: stringNumbers) {
        this.display = display;
    }
}

My problem is when I create a new class. My value is types how I would like it but I have to enter a string for display like this.

let newMyClass = new MyClass('Two');

This is fine for simple objects, vscode will show what types I can use but there isn't any intellisense, And gets very messy when you have anything more advanced.

What I would like to have is an enum or object with properties named the same as the string literal and whose value is the string value like this

enum nums = {
    One,
    Two,
    Three
}

or

let nums = {
    One: 'One';
    Two: 'Two';
    Three: 'Three';
}

That way when I make a new class I can do this

let newMyClass = new MyClass(nums.One);

Any advice on how to make these class declarations better? I love the string literal types but they become almost as useless as just setting it to a string type on complex objects. In my use case I want to bind a form field to a property on a model, but that is in the middle of a bunch of other options for a field so the tooltips are very cluttered.

1 Answer 1

2

If you want to use an enum then:

enum nums {
    One,
    Two,
    Three
}

class myClass {
    display: nums;

    constructor(display: nums) {
        this.display = display;
    }
}

new myClass(nums.One);

If you want to use the enum but want to have the string value (name) and not the ordinal then:

class myClass {
    display: string;

    constructor(display: nums) {
        this.display = display[display];
    }
}

If you want to use the object and pass a key as string:

let nums = {
    One: 'One',
    Two: 'Two',
    Three: 'Three'
}

type keys = keyof typeof nums;

class myClass {
    display: string;

    constructor(display: keys) {
        this.display = nums[display];
    }
}

new myClass("One");
Sign up to request clarification or add additional context in comments.

Comments

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.