Home > Enterprise >  as keyword for enum in typescript?
as keyword for enum in typescript?

Time:09-01

I have this type

type Abc = 'a' | 'b' | 'c'

how can I make myObj.something type Abc?

I can think of valueOf:

const myObj = {
    something: ['a', 'b', 'c'] as valueOf Abc
}

but I wonder why it doesn't work

https://www.typescriptlang.org/play?#code/C4TwDgpgBAggRgYygXigcgIZqgH3XbPNBNAKFEigDcMAbAVwgHsAzAHgBUA FKDgbQDWEEKz4BdUqQRMAdgGdgUALYgA8nABWvAN6koBqPKbKIwABYBLWQHMAXFH6Y0AGnyv0JcVAzzqdRjV2eAQuUgBfIA

CodePudding user response:

in your case you are trying to set ['a', 'b', 'c'] (which is an array) as Abc. You should define myObj.something as an array of type Abc, with Abc[]

const myObj = {
    something: ['a', 'b', 'c'] as Abc[]
}

CodePudding user response:

Please make a interface first. Then use it. Like this

type Abc = 'a' | 'b' | 'c'

// make interface
interface myObject {
    something: Abc[]
}

// use the interface
const myObj:myObject = {
    something: ['a']
}
  • Related