小编Jac*_*ack的帖子

如何使Typescript推断对象的键,但定义其值的类型?

我想定义一个对象的类型,但是让typescript推断出键并且没有那么多的开销来制作和维护所有键的UnionType.

键入一个对象将允许所有字符串作为键:

const elementsTyped: { 
    [key: string]: { nodes: number, symmetric?: boolean }
} = {
    square: { nodes: 4, symmetric: true },
    triangle: { nodes: 3 }
}

function isSymmetric(elementType: keyof typeof elementsTyped): boolean {
    return elementsTyped[elementType].symmetric;
}
isSymmetric('asdf'); // works but shouldn't
Run Code Online (Sandbox Code Playgroud)

推断整个对象将显示错误并允许所有类型的值:

const elementsInferred = {
    square: { nodes: 4, symmetric: true },
    triangle: { nodes: 3 },
    line: { nodes: 2, notSymmetric: false /* don't want that to be possible */ }
}

function isSymmetric(elementType: keyof …
Run Code Online (Sandbox Code Playgroud)

typescript

7
推荐指数
2
解决办法
609
查看次数

标签 统计

typescript ×1