programing

TypeScript의 개체 리터럴에 정의를 입력합니다.

showcode 2023. 3. 6. 21:38
반응형

TypeScript의 개체 리터럴에 정의를 입력합니다.

TypeScript 클래스에서는 다음과 같은 속성 유형을 선언할 수 있습니다.

class className {
  property: string;
};

개체 리터럴에서 속성 유형을 선언하려면 어떻게 해야 합니까?

다음 코드를 시도했지만 컴파일되지 않습니다.

var obj = {
  property: string;
};

다음의 에러가 표시됩니다.

현재 범위에 'string' 이름이 없습니다.

제가 뭘 잘못했나요? 아니면 버그인가요?

친해졌네요, '아까', '아까', '아까', '아까'만요.= a :오브젝트 타입 리터럴(스펙섹션 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 };
  • 이렇게 하면 명시적으로 입력할 필요 없이 모든 항목을 올바르게 입력할 수 있습니다.
  • 필드 이름을 다시 입력할 필요가 없습니다.
  • 이것은 내 경험상 가장 깨끗한 코드로 이어진다.
  • 이를 통해 컴파일러는 더 많은 상태 검증을 제공할 수 있습니다(예를 들어, 여러 위치에 있는 경우 컴파일러는 항상 같은 유형의 오브젝트가 반환되도록 합니다). 즉, 각 위치에서 반환값 전체를 선언하도록 권장하며, 이 값에 대한 명확한 의도를 제공합니다).

보너스: 옵션 필드 2022-09-29

const id = getId();
const optionalField = getOptionalValue();
return {
    id,
    // This will always exist as a key in the object but it might be undefined
    optionalField,
    // This will only exist as a key in the object if it has a truthy value
    ...optionalField2 ? { optionalField } : {},
    // This will only exist as a key in the object if it is not null or undefined
    ...optionalField2 != null ? { optionalField } : {},
};

추가 2020-02-26

쉽게 초기화할 수 있는 유형이 실제로 필요한 경우: Null(늘) 또는 Type(null(유형)으로 표시합니다.타입 시스템은, 우선 가치를 확인하지 않고는 사용할 수 없습니다.

»tsconfig.json늘체크를 유효하게 해

"strictNullChecks": true

그런 다음 다음 다음 패턴을 사용하여 유형 시스템이 실수로 null/정의되지 않은 액세스로부터 사용자를 보호할 수 있도록 합니다.



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)

하다를 사용하세요.asTSX ts ts ts 。

var obj = {
    property: null as string
};

더 긴 예:

var call = {
    hasStarted: null as boolean,
    hasFinished: null as boolean,
    id: null as number,
};

원답

캐스트 연산자를 사용하여 (null을 원하는 유형에 캐스팅하여) 간결하게 만듭니다.

var obj = {
    property: <string> null
};

더 긴 예:

var call = {
    hasStarted: <boolean> null,
    hasFinished: <boolean> null,
    id: <number> null,
};

이것은, 2개의 부분(하나는 타입을 선언하는 부분, 다른 하나는 디폴트를 선언하는 부분)을 가지는 것보다 훨씬 우수합니다.

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,
  // ...
};

또, 이 인터페이스를 필요한 만큼, 원하는 수의 오브젝트로 재이용할 수 있는 것도 장점도 있습니다.

행운을 빌어요.

사전 정의된 유틸리티 유형을 사용할 수 있습니다.

const obj: Record<string, string> = {
  property: "value",
};

오브젝트 리터럴의 키를 지정할 수 있습니다.

type Keys = "prop1" | "prop2"

const obj: Record<Keys, string> = {
  prop1: "Hello",
  prop2: "Aloha",
  something: "anything" // TS Error: Type '{ prop1: string; prop2: string; something: string; }' is not assignable to type 'Record<Keys, string>'.
                        //   Object literal may only specify known properties, and 'something' does not exist in type 'Record<Keys, string>'.
};

속성 값의 유형:

type Keys = "prop1" | "prop2"
type Value = "Hello" | "Aloha"

const obj1: Record<Keys, Value> = {
  prop1: "Hello",
  prop2: "Hey", // TS Error: Type '"Hey"' is not assignable to type 'Value'.
};

유형 주석을 작성하려는 경우 구문은 다음과 같습니다.

var x: { property: string; } = { property: 'hello' };

오브젝트 리터럴을 쓰려는 경우 구문은 다음과 같습니다.

var x = { property: 'hello' };

코드가 값 위치에 형식 이름을 사용하려고 합니다.

를 들어 함수의 인수와 같이 구조화되지 않은 오브젝트 리터럴에 타이핑을 추가하려고 할 경우 구문은 다음과 같습니다.

function foo({ bar, baz }: { bar: boolean, baz: string }) {
  // ...
}

foo({ bar: true, baz: 'lorem ipsum' });

TypeScript에서는 오브젝트를 선언하는 경우 다음 구문을 사용합니다.

[access modifier] variable name : { /* structure of object */ }

예를 들어 다음과 같습니다.

private Object:{ Key1: string, Key2: number }

주의하세요. 어떤 이들에게는 명백하게 보일지 모르지만, 형식 선언은 다음과 같습니다.

const foo: TypeName = {}

요.as:

const foo = {} as TypeName

다른 답변에 사용하자는 제안에도 불구하고요

예:

고마워, 활자 안전!:

const foo: { [K in 'open' | 'closed']: string } = {}
// ERROR: TS2739: Type '{}' is missing the following properties from type '{ open: string; closed: string; }': open, closed

안녕, 타입 세이프티!:

const foo = {} as { [K in 'open' | 'closed']: string }
// No error

2021년에 TypeScript 4.5를 사용하여 다음과 같은 작업을 수행하고 있습니다.

const sm = {
  reg: {} as ServiceWorkerRegistration,
  quantum: null as number | null,
  currentCacheName: '' as string, // superfluous
  badSWTimer: 0 as number, // superfluous
}

이는 단순한 값 캐스트가 아니라 오브젝트 속성에 대한 인터페이스 정의와 동일하게 동작합니다.

업데이트: 예시로 불필요한 오타를 2개 포함했습니다.즉, 이러한 입력은 자동으로 추론될 수 있으므로 컴파일러 오류를 생성하지 않습니다.

출처 : 4.4 Playground

// Use ..

const Per = {
  name: 'HAMZA',
  age: 20,
  coords: {
    tele: '09',
    lan: '190'
  },
  setAge(age: Number): void {
    this.age = age;
  },
  getAge(): Number {
    return age;
  }
};
const { age, name }: { age: Number; name: String } = Per;
const {
  coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;

console.log(Per.getAge());

코드:

var obj = {
  myProp: string;
};

실제로 개체 리터럴을 만들고 변수 문자열을 myProp 속성에 할당합니다.매우 나쁜 관행이지만 실제로는 유효한 TS 코드입니다(이 코드를 사용하지 마십시오).

var string = 'A string';

var obj = {
  property: string
};

단, 오브젝트 리터럴이 입력되어 있어야 합니다.이는 다양한 방법으로 달성할 수 있습니다.

인터페이스:

interface myObj {
    property: string;
}

var obj: myObj = { property: "My string" };

유형 별칭:

type myObjType = {
    property: string
};

var obj: myObjType = { property: "My string" };

개체 유형 리터럴:

var obj: { property: string; } = { property: "Mystring" };
  1. type 키워드를 사용하여 유형을 작성하다
type ObjType = {
  property: string;
}

그런 다음 다음과 같이 개체를 바인딩하여 이 유형만 수락할 수 있습니다.

const obj: ObjType = {
property: "TypeScript"
}

개체 리터럴을 DRY를 사용하여 유형으로 변환

다음 작업을 수행합니다.

const myObject = {
   hello: 'how are you',
   hey: 'i am fine thank you'
}
type myObjectType = keyof typeof MyObject

됐다!

@RickLove의 답변을 연장하기 위해...

유추할 수 없는 유형만 정의하면 되므로 이 방법은 매우 효과적입니다.

const initialState = { 
   user: undefined as User | undefined, 
   userLoading: false
}; 

다음 js 코드로 변환됩니다.

const initialState = { 
   user: undefined, 
   userLoading: false
};  

타입으로 추출할 필요가 있는 경우는, 다음과 같이 할 수 있습니다.

export type InitState = typeof initialState;

언급URL : https://stackoverflow.com/questions/12787781/type-definition-in-object-literal-in-typescript

반응형