문제 설명
TypeScript, VSCode: vscode의 내부 버전으로 전환할 때 keyof 유형이 예상대로 작동하지 않습니다. (TypeScript, VSCode: keyof type not working as expected when switching to insider version of vscode)
최근에 성능 문제로 인해 VSCode에서 VSCode ‑ Insiders(기본적으로 야간 빌드)로 전환했으며 어떤 이유로 코드에 새로운 Linting 오류가 발생합니다. TypeScript 버전 3.5.1을 사용하고 있습니다.
다음은 단순화된 예입니다.
private updateTransaction = (
k: 'description' | 'amount' | 'timestamp' | 'vendorId',
v: ITransaction['description' | 'amount' | 'timestamp' | 'vendorId']
) => {
if(this.state.selectedTransaction){
this.state.selectedTransaction[k] = v;
}
};
여기서 ITransaction
은 다음과 같습니다.
export interface ITransaction {
description: string;
amount: number;
timestamp: string;
vendorId: number;
}
내부자 빌드로 전환하기 전에는 오류가 아니었지만 VSCode TypeScript의 내부자 버전에서 동일한 프로젝트를 열면 다음과 같이 불평합니다.
Type 'string | number'는 'string & number'.
유형 '문자열'은 유형 '문자열 & 번호'.
<블록 인용>'문자열' 유형은 '숫자' 유형에 할당할 수 없습니다.
여기서 무슨 일이 일어나고 있는지 이해하는 데 도움을 줄 수 있는 사람이 있습니까? 이것이 VSCode 내부자 빌드의 버그인지 또는 내 입력이 올바르지 않고 이 오류 메시지가 진정으로 나에게 의미가 없는지 확실하지 않습니다. type KeyType = keyof Interface
및 Interface[KeyType]
패턴을 자주 사용하는데 이 오류 메시지는 본 적이 없습니다.
The basic idea is that until now typescript allowed write operations to obj[k] = v
where k: keyof typeof obj
if v
was a union of possible values in obj
:
let o = { nr: 0, str: "" }
declare let k: keyof typeof o;
o[k] = 0
o[k] = ""
This was unsound. The example above works in 3.4 and below, but if k
is 'nr'
then the second assignment put o
in an invalid state. If k
is 'str'
then the first assignment puts the object in an invalid state.
The simple solution is to use a type assertion:
function updateTransaction(k: TransactionKey, v: ITransaction[TransactionKey]) {
if (testState.selectedTransaction) {
testState.selectedTransaction[k] = v as any;
}
}
This is still unsound, but not more so than before.
(by Robbie Milejczak、Titian Cernicova‑Dragomir)