이 코드 줄에서 아래 오류가 계속 발생합니다 oldUniforms[key] = tempUniforms[key];
.. 동일한 유형의 객체에 대한 깊은 사본을 생성하기 때문에 이것이 작동하지 않는 이유를 이해할 수 없습니다.
오류:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'UpdatedUniformsType'.
No index signature with a parameter of type 'string' was found on type 'UpdatedUniformsType'.ts(7053)
암호:
type UpdatedUniformsType = {
u_BlockDia?: number;
u_CamPos?: [number, number];
};
const oldUniforms: UpdatedUniformsType = {
u_BlockDia: 16,
u_CamPos: [0, 0],
};
function setOldUniforms(updatedUniforms: UpdatedUniformsType) {
// Deep copy of updatedUniforms
const tempUniforms: UpdatedUniformsType = JSON.parse(JSON.stringify(updatedUniforms));
// Update oldUniforms using the deep copy
Object.keys(tempUniforms).forEach((key) => {
oldUniforms[key] = tempUniforms[key];
});
}
컴파일러는 모르는 Object.keys(tempUniforms)
생산합니다 에만 예상 키를. TypeScript의 객체 유형은 개방 / 확장 가능 하며 폐쇄 / 정확 하지 않습니다 . 유형의 객체가 있으면 및 키 UpdatedUniformsType
에서 일어나는 일에 대해 의미있게 말할 수 있지만 추가 속성이 있는지 여부는 알 수 없습니다. 그래서 A는 반환 타이프 라이터에, 아닌 . 자세한 내용은 이 질문 과 답변을 참조하십시오.u_BlockDia
u_CamPos
Object.keys(obj)
string[]
Array<keyof typeof obj>
추가 키가 없다고 확신하는 경우 (또는 추가 키가있을 때 어떤 일이 발생하는지 신경 쓰지 않는 경우) 유형 어설 션 을 사용 하여 컴파일러 가 반환 할 것임을 알릴 수 있습니다 .Object.keys(tempUniforms)
Array<keyof UpdatedUniformsType>
(Object.keys(tempUniforms) as Array<keyof UpdatedUniformsType>)
.forEach(<K extends keyof UpdatedUniformsType>(key: K) => {
oldUniforms[key] = tempUniforms[key];
});
또한 forEach()
콜백을 제네릭 함수 로 만들어 oldUniforms[key] = tempUniforms[key]
컴파일러가 할당 UpdatedUniformsType[K]
을 자체 할당으로 인식 하도록해야했습니다. 그렇게하지 않으면 컴파일러는 TS3.5에 도입 된 건전성 향상 으로 인해 할당이 안전하다는 것을 인식하지 못합니다 . 자세한 내용은 이 질문 과 답변을 참조하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다