Want to make variables of defined type read-only

Asked 1 years ago, Updated 1 years ago, 57 views

For example, define the following types of Options:

interface Options {
    "encoding":string,
    "initValue"?—any
}

When preparing variables options, I would like to declare variables as read-only while inheriting the input complement of the type when editing the variable contents.
The following code will not work for me, but please take it as an image.

 constoptions=<Options>{
    // Naturally, you can complement the input of the Options type here.
    "encoding": "String",
    "initValue": "test"
} as const;// eventually declared read-only

Therefore, when focusing on the variable options in the editor,

 constoptions:options

Not

 construction options: {
    readonly encoding: "String";
    readonly initValue: "test";
}

I'd like to display it as

typescript

2022-09-30 18:01

1 Answers

Readonly<Type> will make this a reality.

constant options:Readonly<Options>={
    encoding: "String",
    initValue: "test",
}

However, the type of options that appears during editing may depend on the editor's settings, but it will probably be Readonly<Options>.


2022-09-30 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.