TypeScript에서 형식을 nullable로 선언하는 방법은 무엇입니까?


249

TypeScript에 인터페이스가 있습니다.

interface Employee{
    id: number;
    name: string;
    salary: number;
}

salaryC #에서 할 수있는 것처럼 nullable 필드 로 만들고 싶습니다 . 이것이 TypeScript에서 가능합니까?

답변:


277

JavaScript (및 TypeScript)의 모든 필드는 null또는 값을 가질 수 있습니다 undefined.

널 입력 가능과 다른 필드를 선택적으로 만들 수 있습니다 .

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

다음과 비교하십시오 :

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

35
과 같은 엄격 null 허용 유형 및 고정 널 검사를 구현하고 타이프 2.0 도착합니다! (또는 typescript@next현재)
mindplay.dk

첫 번째 예에서 var c에 대해 확신하십니까? var b와 var c가 같은 것 같습니다.
martinp999

컴파일 오류없이 널 또는 정의되지 않은 값을 설정하려면 tsconfig "strict"옵션을 제거하거나 "false"와 동일해야합니다."strict" : false
Nicolas Janel

1
이것은 올바르지 않습니다. JS는 null과 undefined를 구분합니다. 올바른 코드가 있어야한다 salary:number|null;당신이 할 경우, salary?:number; salary = null;당신은 오류가 발생합니다. 그러나이 salary = undefined;경우에는 잘 작동합니다. 솔루션 : Union 즉 '|'사용
Ankur Nigam

126

이 경우 유니온 유형이 최선의 선택입니다.

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

편집 : 예상대로 작동하려면 strictNullChecks in을tsconfig .


9
--strictNullChecks (필요한)를 사용하는 경우 유효한 솔루션입니다. 모든 리터럴 객체에 명시 적으로 null을 추가해야하지만 함수 반환 값의 경우 갈 수있는 방법이므로 선택적 멤버를 선호하지 않습니다.
geon

78

C # 처럼 하려면 다음 과 같이 Nullable유형을 정의하십시오 .

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}

보너스:

Nullable내장 된 Typescript 유형처럼 동작 하려면 global.d.ts루트 소스 폴더 의 정의 파일에서 정의하십시오. 이 길은 나를 위해 일했다 :/src/global.d.ts


1
내가 가장 좋아하는 답변- 질문을 읽지 않고 직접 답변합니다.
Lqueryvg

1
이를 사용하면 객체 속성의 자동 완성이 중단됩니다. 예를 들어 emp: Partial<Employee>, 우리가 할 수 emp.id있거나 할 수는 emp.name있지만 우리가 emp: Nullable<Employee>할 수 없다면 할 수 없습니다emp.id
Yousuf Khan

1
이것이 실제 질문에 대한 답변입니다.
패트릭

37

?옵션 필드에 물음표 를 추가하십시오 .

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

54
라이언이 지적했듯이 ...? typescript에서 선택 사항이며 널 입력 가능하지 않음을 의미합니다. 없이? var가 null 또는 undefined를 포함하는 값으로 설정되어야 함을 의미합니다. ? 선언 전체를 건너 뛸 수 있습니다.
그는 Nrik

3
감사합니다! "typescript optional value"를 검색 했으므로 이것이 바로 내가 찾던 것입니다.
동료 낯선 사람

13

다음과 같이 사용자 정의 유형을 구현할 수 있습니다.

type Nullable<T> = T | undefined | null;

var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok

var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok

 // Type 'number[]' is not assignable to type 'string[]'. 
 // Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];


4

void가 같은 유형의 질문을 가지고 있습니다. void는 모든 유형의 하위 유형이기 때문에 (예 : scala와는 달리) ts의 모든 유형은 nullable입니다.

이 흐름도가 도움이되는지 확인하십시오-https: //github.com/bcherny/language-types-comparison#typescript


2
-1 : 이것은 사실이 아닙니다. 에 관해서는 void'모든 유형의 하위 유형'(인 바닥 유형 )를 참조하십시오 이 스레드 . 또한 스칼라에 제공 한 차트도 올바르지 않습니다. Nothing스칼라에서 실제로는 바닥 유형입니다. scala typescript, atm에 bottom 유형 이 없습니다 .
Daniel Shin

2
"모든 유형의 하위 유형"! = 하단 유형. TS 사양 github.com/Microsoft/TypeScript/blob/master/doc/…를
bcherny

3

널 입력 가능 유형은 런타임 오류를 호출 할 수 있습니다. 그래서 컴파일러 옵션을 사용하고 유형으로 --strictNullChecks선언 하는 것이 좋습니다 number | null. 또한 중첩 함수의 경우 입력 유형이 null이지만 컴파일러가 중단 할 수있는 것을 알 수 없으므로 사용 !(exclamination mark)을 사용하는 것이 좋습니다 .

function broken(name: string | null): string {
  function postfix(epithet: string) {
    return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null
  }
  name = name || "Bob";
  return postfix("great");
}

function fixed(name: string | null): string {
  function postfix(epithet: string) {
    return name!.charAt(0) + '.  the ' + epithet; // ok
  }
  name = name || "Bob";
  return postfix("great");
}

참고. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.