hyundeock
hyundeock

Reputation: 505

Proper typescript type aliasing

I want to apply proper alias type in typescript.

[Example]


type O = {
    a?: "aa",
    b?: "bb",
    c?: "cc"
}
type Str = 'a' | 'b' | 'c';
type ReturnOfFoo = 'aa' | 'bb' | 'cc';

const o: O = {};

const foo = (str: Str): ReturnOfFoo => {
    if(str === 'a') return 'aa';
    if(str === 'b') return 'bb';
    return 'cc';
}

const createRandomStr = (): Str => ['a', 'b', 'c'][Math.floor(Math.random() * 3)] as Str;

const key: Str = createRandomStr();
const value: ReturnOfFoo = foo(key);

o[key] = value // o[key] error occured!

So, I did use "If statement" below.

if(key === 'a') {
  o[key] = value as 'aa';
}

if(key === 'b') {
  o[key] = value as 'bb';
}

if(key === 'c') {
  o[key] = value as 'cc';
}

But, it is not cool.

I did write more code for type.

Is there a better way?

I can use "any" type, but that's also not a good idea.

Upvotes: 1

Views: 50

Answers (1)

Eldar
Eldar

Reputation: 10790

Edit Sorry for the misunderstanding at first glance.

Adding a cast to the last line will resolve your issue :

(o[key] as ReturnOfFoo) = value

Playground Link

Upvotes: 1

Related Questions