正确的打字稿类型别名

时间:2020-10-01 07:02:34

标签: typescript

我想在打字稿中应用适当的别名类型。

[示例]


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!

因此,我确实在下面使用了“ If语句”。

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

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

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

但是,这并不酷。

我确实为类型编写了更多代码。

有更好的方法吗?

我可以使用“任何”类型,但这也不是一个好主意。

1 个答案:

答案 0 :(得分:1)

编辑抱歉,乍看之下的误解。

在最后一行添加演员表将解决您的问题:

(o[key] as ReturnOfFoo) = value

Playground Link