这是 my question 的第二部分被问到here 。我得到了上一个问题的解决方案的帮助,但是一旦我添加了 alphabet
对象的接口(interface),Typescript 就停止检测我提供了不正确的值。
interface ICharMap {
lower: number
upper: number
}
const alphabet: {[key: string]: ICharMap} = {
'a': {lower: 97, upper: 65},
'b': {lower: 98, upper: 66}
}
type Char = keyof typeof alphabet;
function printSome(char: Char){
console.log(char)
}
printSome('c') \\ Typescript does not detect that the incorrect value is passed.
最佳答案
你可以这样做:
interface ICharMap {
lower: number
upper: number
}
type Letter = 'a' | 'b'
const alphabet: Record<Letter, ICharMap> = {
'a': {lower: 97, upper: 65},
'b': {lower: 98, upper: 66}
}
function printSome(char: Letter){
console.log(char);
console.log(alphabet[char]); // no error; TS knows that char is in alphabet
}
printSome('c') // error
关于javascript - Typescript:使用接口(interface)从对象生成类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71136635/