Saturday, April 17, 2021

TypeScript, array map can't be type-checked

Given this interface:
	interface IHskLevel {
       hanzi: string;
       hsk: number;
    }
This code does not produce compile error (it should):
function* generateHskLevel(): Iterable<IHskLevel> {
    yield* json.map(
        ({ hanzi, pinyin, HSK: hsk }) => ({ hanzi, pinyin, hsk })
    );
}
This produces compile error (it should):
function* generateHskLevel(): Iterable<IHskLevel> {
    for (const { hanzi, pinyin, HSK: hsk } of json) {
        yield { hanzi, pinyin, hsk };
    }
}
Error:
error: TS2322 [ERROR]: Type '{ hanzi: string; pinyin: string; hsk: number; }' is not assignable to type 'IHskLevel'.
  Object literal may only specify known properties, and 'pinyin' does not exist in type 'IHskLevel'.
            pinyin,

No comments:

Post a Comment