TypeScript 클래스에서는 다음과 같이 속성 유형을 선언 할 수 있습니다.
class className {
property: string;
};
객체 리터럴에서 속성 유형을 어떻게 선언합니까?
다음 코드를 시도했지만 컴파일되지 않습니다.
var obj = {
property: string;
};
다음과 같은 오류가 발생합니다.
현재 범위에 ‘string’이름이 없습니다.
내가 잘못하고 있거나 버그입니까?
답변
당신은 꽤 가깝습니다. 당신은로 대체해야 =
합니다 :
. 객체 유형 리터럴 (사양 섹션 3.5.3 참조) 또는 인터페이스를 사용할 수 있습니다. 객체 타입 리터럴을 사용하는 것은 당신이 가진 것에 가깝습니다.
var obj: { property: string; } = { property: "foo" };
그러나 인터페이스를 사용할 수도 있습니다
interface MyObjLayout {
property: string;
}
var obj: MyObjLayout = { property: "foo" };
답변
2019-05-15 업데이트 (대체 코드 패턴 개선)
const
더 많은 기능 코드 를 사용 하고 혜택을 얻은 후에 수년이 지난 후 대부분의 경우 아래를 사용하지 않는 것이 좋습니다. (객체를 만들 때 유형 시스템을 유형을 유추하지 않고 특정 유형으로 강제하는 것은 종종 무언가 잘못되었음을 나타냅니다).
대신 const
가능한 한 변수를 사용 하고 객체를 마지막 단계로 작성하는 것이 좋습니다 .
const id = GetId();
const hasStarted = true;
...
const hasFinished = false;
...
return {hasStarted, hasFinished, id};
- 이렇게하면 명시 적으로 입력 할 필요없이 모든 것을 올바르게 입력합니다.
- 필드 이름을 다시 입력 할 필요가 없습니다.
- 이것은 내 경험에서 가장 깨끗한 코드로 이어집니다.
- 이를 통해 컴파일러는 더 많은 상태 확인을 제공 할 수 있습니다 (예를 들어, 여러 위치로 반환하는 경우 컴파일러는 동일한 유형의 객체가 항상 반환되도록합니다. 이렇게하면 각 위치에서 전체 반환 값을 선언하도록 장려 함) 그 가치의 의도).
추가 2020-02-26
실제로 초기화 할 수있는 유형이 필요한 경우 : 널 입력 가능 결합 유형 (널 또는 유형)으로 표시하십시오. 타입 시스템은 먼저 값을 가지지 않고 사용하지 못하게합니다.
에 tsconfig.json
엄격한 null 검사를 활성화해야합니다.
"strictNullChecks": true
그런 다음이 패턴을 사용하여 유형 시스템이 우발적 인 널 / 정의되지 않은 액세스로부터 보호합니다.
const state = {
instance: null as null | ApiService,
// OR
// instance: undefined as undefined | ApiService,
};
const useApi = () => {
// If I try to use it here, the type system requires a safe way to access it
// Simple lazy-initialization
const api = state?.instance ?? (state.instance = new ApiService());
api.fun();
// Also here are some ways to only access it if it has value:
// The 'right' way: Typescript 3.7 required
state.instance?.fun();
// Or the old way: If you are stuck before Typescript 3.7
state.instance && state.instance.fun();
// Or the long winded way because the above just feels weird
if (state.instance) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans way
if (state.instance != null) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans
// AND I was told to always use triple === in javascript even with null checks way
if (state.instance !== null && state.instance !== undefined) { state.instance.fun(); }
};
class ApiService {
fun() {
// Do something useful here
}
}
99 %의 경우 아래를 수행하지 마십시오.
2016-02-10 업데이트-TSX 처리 (감사 @Josh)
as
TSX 에는 연산자를 사용하십시오 .
var obj = {
property: null as string
};
더 긴 예 :
var call = {
hasStarted: null as boolean,
hasFinished: null as boolean,
id: null as number,
};
원래 답변
캐스트 연산자를 사용하여 간결하게 만드십시오 (널을 원하는 유형으로 캐스트하여).
var obj = {
property: <string> null
};
더 긴 예 :
var call = {
hasStarted: <boolean> null,
hasFinished: <boolean> null,
id: <number> null,
};
두 부분으로 구성하는 것 (하나는 형식을 선언하고 다른 하나는 기본값을 선언하는 것)보다 훨씬 낫습니다.
var callVerbose: {
hasStarted: boolean;
hasFinished: boolean;
id: number;
} = {
hasStarted: null,
hasFinished: null,
id: null,
};
답변
아무도 이것을 언급하지 않은 것에 놀랐습니다.하지만 유형의 쌍 ObjectLiteral
을 허용 하는 인터페이스를 만들 수 있습니다 .key: value
string: any
interface ObjectLiteral {
[key: string]: any;
}
그런 다음 다음과 같이 사용하십시오.
let data: ObjectLiteral = {
hello: "world",
goodbye: 1,
// ...
};
또한 보너스는 원하는 수의 객체에서이 인터페이스를 필요한만큼 여러 번 재사용 할 수 있다는 것입니다.
행운을 빕니다.
답변
타입 주석을 작성하려는 경우 구문은 다음과 같습니다.
var x: { property: string; } = ...;
객체 리터럴을 작성하려는 경우 구문은 다음과 같습니다.
var x = { property: 'hello' };
코드가 값 위치에 유형 이름을 사용하려고합니다.
답변
TypeScript에서 객체를 선언하면 다음 구문을 사용합니다.
[access modifier] variable name : { /* structure of object */ }
예를 들면 다음과 같습니다.
private Object:{ Key1: string, Key2: number }
답변
당신이에 typings를 추가하려는 경우 탈구 함수에 인수 예를 들어, 객체 리터럴, 구문은 다음과 같습니다
function foo({ bar, baz }: { bar: boolean, baz: string }) {
// ...
}
foo({ bar: true, baz: 'lorem ipsum' });
답변
속성의 유형이 동일한 경우 사전 정의 된 유틸리티 유형을 사용할 수 있습니다 Record
.
type Keys = "property" | "property2"
var obj: Record<Keys, string> = {
property: "my first prop",
property2: "my second prop",
};
더 나아가서 속성 값에 대한 사용자 정의 유형을 정의 할 수 있습니다.
type Keys = "property" | "property2"
type Value = "my prop" | "my other allowed prop"
var obj: Record<Keys, Value> = {
property: "my prop",
property2: "my second prop", // TS Error: Type '"my second prop"' is not assignable to type 'Value'.
};
