programing

'as const'를 유형과 결합하시겠습니까?

javamemo 2023. 6. 9. 21:41
반응형

'as const'를 유형과 결합하시겠습니까?

나는 상수에 대한 유형을 갖는 것과 그것을 "as const"로 사용하는 것을 결합하여 문자형을 다음 유형으로 얻고자 합니다.

type MyType = {name: string};

const x:MyType = {
    name: 'test' // Autocompleted, typesafe. But Type is {name: string}, not 
                 // what I want, {name: 'test'}
}

const x = { name: 'test' } as const; // Gives correct type, but no type check...

어떻게 하는 거지?

2022년 9월 편집:

Typescript 4.9에서는 연산자를 사용할 수 있습니다.

type MyType = { name: string }

const x ={
  name: 'test', // Autocompleted, typesafe
} as const satisfies MyType

x.name // type is 'test' (not string)

그리고 어떤 이유로, 당신은 사용할 수 없습니다.satisfies동일한 동작을 복제하는 것은 매우 쉽습니다.

/**
 * Replacement for TS satisfies operator, until it's well supported
 * Usage:
 * const test = satisfy<{ a: string }>()({ a: 'test', b: 'test' })
 * */
export function satisfy<TSatisfied>(): <T extends TSatisfied>(value: T) => T {
  return (value) => value
}

이전 솔루션:

원하는 것을 달성할 수 있는 방법은 다음과 같습니다.

type MyType = { name: string }

// This function does nothing. It just helps with typing
const makeMyType = <T extends MyType>(o: T) => o

const x = makeMyType({
  name: 'test', // Autocompleted, typesafe
} as const)

x.name // type is 'test' (not string)

유형을 확인할 필요가 없습니다.{name: "test"} as const왜냐하면 Typescript는 구조적 평등 의미를 사용하기 때문입니다.{name: "test"} as constMyType의 구조가 동일하므로 동일합니다.

이 동작은 이러한 도우미 유형을 사용하여 관찰할 수 있습니다.

interface MyType {
     name: string;
}
const test = {name: "test"} as const;
type IsEqual<T, U> = [T] extends [U] ? true : false;
type AreTheyEqual = IsEqual<typeof test, MyType> // true they are the same.

MyType을 응시하는 모든 항목은 유형의 테스트를 응시할 수 있습니다.

편집: 유형 검사 테스트를 위해 강제로 MyType 유형 검사 테스트를 수행하려면 문자열 리터럴을 유지하여 수행할 수 없습니다. MyType이라고 주장되는 모든 항목이 리터럴 유형을 잃고 문자열로 되돌아가기 때문입니다. 이 동작은 여기에서 확인할 수 있습니다.

type MyType = {name: string};
const x:MyType = {
    name: 'test' as const
}
type Test = typeof x["name"] // string;

즉, MyType에서 Literal과 string type을 모두 사용하려면 대신 이와 같은 작업을 수행해야 합니다(MyType 변경).이것을 사용하는 것은 장황해 보이지만 거의 틀림없이 "as const"보다 덜 상용화되어 있습니다.

interface MyType<NAME extends string = string> {
    name: NAME;
}
const x: MyType = {
    name: 'test' // string;
}
const y: MyType<"test"> = {
    name: "test" // "test"
}

type Test1 = typeof x["name"]// string;
type Test = typeof y["name"] // "test";

문자열 및 리터럴 형식이 모두 허용됩니다.

저는 어떤 원시적인 지원도 없다고 생각합니다.그러나 유형 어설션을 사용하여 다른 const를 정의하여 유형 검사를 수행할 수 있습니다.

type MyType = {name: string};

const x = {
    name: 'test' 
} as const

const xTypeCheck = typeof (x as MyType) // Check the type of x as MyType 

참고: x 값의 참조를 피하기 위해 'type of'를 사용하므로 다른 참조가 없는 경우 x 값을 삭제할 수 있습니다.

언급URL : https://stackoverflow.com/questions/56694082/as-const-combined-with-type

반응형