programing

"오브젝트 리터럴은 알려진 속성만 지정할 수 있습니다"라는 오류가 표시되는 이유는 무엇입니까?

nicescript 2023. 2. 15. 23:03
반응형

"오브젝트 리터럴은 알려진 속성만 지정할 수 있습니다"라는 오류가 표시되는 이유는 무엇입니까?

방금 TypeScript 1.5에서 최신 버전으로 업그레이드했는데 코드에 오류가 있습니다.

interface Options {
   /* ... others ... */
   callbackOnLocationHash?: boolean;
}

function f(opts: Options) { /* ... */ }

//  Error: Object literal may only specify known properties,
//     and 'callbackOnLoactionHash'does not exist in type 'Options'.
f( { callbackOnLoactionHash: false });

코드는 괜찮을 것 같아.뭐가 잘못됐나요?

(대체 우주 버전:오타를 알아봤는데 정말 쓰려고 했어요.오류를 제거하려면 어떻게 해야 합니까?

TypeScript 1.6에서는 개체 리터럴에서 할당된 유형의 속성이 없는 속성은 오류로 플래그가 지정됩니다.

일반적으로 이 오류는 코드 또는 정의 파일에 버그(일반적으로 오타)가 있음을 의미합니다.이 경우의 올바른 수정은 오타를 수정하는 것입니다.질문에서 속성은callbackOnLoactionHash틀렸기 때문에 틀렸어야 했다.callbackOnLocationHash('Location'의 철자가 틀렸음을 주의해 주십시오).

이 변경에는 정의 파일도 업데이트해야 하므로 사용 중인 라이브러리의 최신 버전의 .d.ts가 필요합니다.

예:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

하지만 난 그럴 생각이었어

오브젝트에 추가 속성이 포함되어 있을 가능성이 있는 경우가 있습니다.수행하는 작업에 따라 몇 가지 적절한 수정이 있습니다.

일부 속성만 형식 검사

경우에 따라서는, 몇개의 것이 존재하고 있고, 올바른 타입의 것을 확인하고 싶은 경우도 있습니다만, 어떠한 이유로든 추가의 속성을 가지고 싶다고 생각하고 있습니다.Assertions를 입력합니다(<T>v또는v as T) 타입 주석 대신 사용할 수 있도록 추가 속성을 체크하지 마십시오.

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

이러한 특성 및 기타 사항

일부 API는 개체를 가져와서 해당 키에서 동적으로 반복하지만 특정 유형의 '특수' 키가 있어야 합니다.문자열 인덱서를 유형에 추가하면 추가 속성 검사가 비활성화됩니다.

전에

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

끝나고

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

이것은 개, 고양이, 말이며 아직 확실하지 않다.

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

여기에서는 두 가지 좋은 솔루션이 떠오릅니다.

다음에 대해 닫힌 세트 지정x

// Removes all errors
let x: Dog|Cat|Horse;

또는 타이프 assert항목을 입력합니다.

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

이 타입은 오픈할 때도 있고 안 할 때도 있습니다.

교차 유형을 사용하여 "데이터 모델" 문제에 대한 깨끗한 해결 방법:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

https://github.com/Microsoft/TypeScript/issues/3755 도 참조해 주세요.

언급URL : https://stackoverflow.com/questions/31816061/why-am-i-getting-an-error-object-literal-may-only-specify-known-properties

반응형